美文网首页
iOS UILabel 添加查看更多

iOS UILabel 添加查看更多

作者: CaptainRoy | 来源:发表于2019-07-27 12:10 被阅读0次

参考链接
参考链接

效果
  • UILabel + ReadMore 分类
#import <UIKit/UIKit.h>

NS_ASSUME_NONNULL_BEGIN

@interface UILabel (ReadMore)

-(void)setReadMoreLabelContentMode;

@end

NS_ASSUME_NONNULL_END
#import "UILabel+ReadMore.h"
#import <CoreText/CoreText.h>

@implementation UILabel (ReadMore)

-(void)setReadMoreLabelContentMode
{
    NSArray *contents = [self getLinesArrayOfLabelRows];
    if (contents.count <= 1) {
        self.userInteractionEnabled = NO; // 如果一行就不显示查看更多,同时取消手势响应
        return;
    }
    self.userInteractionEnabled=YES;
    
    NSUInteger cutLength = 20; // 截取的长度
    
    NSMutableString *contentText = [[NSMutableString alloc] init];
    for (NSInteger i = 0; i < self.numberOfLines; i++) {
        if (i == self.numberOfLines - 1) { // 最后一行 进行处理加上.....
            
            NSString *lastLineText = [NSString stringWithFormat:@"%@",contents[i]];
            NSUInteger lineLength = lastLineText.length;
            if (lineLength > cutLength) {
                lastLineText = [lastLineText substringToIndex:(lastLineText.length - cutLength)];
            }
            [contentText appendString:[NSString stringWithFormat:@"%@.....",lastLineText]];
            
        } else {
            [contentText appendString:contents[i]];
        }
    }
    
    NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
    NSDictionary *dictionary = @{
                                 NSForegroundColorAttributeName : self.textColor,
                                 NSFontAttributeName : self.font,
                                 NSParagraphStyleAttributeName : style
                                 };
    
    NSMutableAttributedString *mutableAttribText = [[NSMutableAttributedString alloc] initWithString:[contentText stringByAppendingString:@"  查看更多"] attributes:dictionary];
    [mutableAttribText addAttributes:@{
                                       NSFontAttributeName : [UIFont boldSystemFontOfSize:14.0f],
                                       NSForegroundColorAttributeName : [UIColor orangeColor]
                                       } range:NSMakeRange(contentText.length, 6)];
    self.attributedText = mutableAttribText;
}

// 获取 Label 每行内容 得到一个数组
- (NSArray *)getLinesArrayOfLabelRows
{
    CGFloat labelWidth = self.frame.size.width;
    
    NSString *text = [self text];
    UIFont *font = [self font];
    if (text == nil) {
        return nil;
    }
    CTFontRef myFont = CTFontCreateWithName(( CFStringRef)([font fontName]), [font pointSize], NULL);
    NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc] initWithString:text];
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineBreakMode = NSLineBreakByCharWrapping;
    [attStr addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, attStr.length)];
    [attStr addAttribute:(NSString *)kCTFontAttributeName
                   value:(__bridge  id)myFont
                   range:NSMakeRange(0, attStr.length)];
    CFRelease(myFont);
    CTFramesetterRef frameSetter = CTFramesetterCreateWithAttributedString(( CFAttributedStringRef)attStr);
    CGMutablePathRef path = CGPathCreateMutable();
    CGPathAddRect(path, NULL, CGRectMake(0,0,labelWidth,100000));
    CTFrameRef frame = CTFramesetterCreateFrame(frameSetter, CFRangeMake(0, 0), path, NULL);
    NSArray *lines = ( NSArray *)CTFrameGetLines(frame);
    NSMutableArray *linesArray = [[NSMutableArray alloc]init];
    for (id line in lines) {
        CTLineRef lineRef = (__bridge  CTLineRef )line;
        CFRange lineRange = CTLineGetStringRange(lineRef);
        NSRange range = NSMakeRange(lineRange.location, lineRange.length);
        NSString *lineString = [text substringWithRange:range];
        CFAttributedStringSetAttribute((CFMutableAttributedStringRef)attStr,
                                       lineRange,
                                       kCTKernAttributeName,
                                       (CFTypeRef)([NSNumber numberWithFloat:0.0]));
        CFAttributedStringSetAttribute((CFMutableAttributedStringRef)attStr,
                                       lineRange,
                                       kCTKernAttributeName,
                                       (CFTypeRef)([NSNumber numberWithInt:0.0]));
        [linesArray addObject:lineString];
    }
    CGPathRelease(path);
    CFRelease(frame);
    CFRelease(frameSetter);
    return (NSArray *)linesArray;
}

@end
  • 例子
NSString *context = @"当最后一行显示不全时,需求有时候需要改变省略号的位置,系统并未提供,但我们可以通过coreText拿到每行的文字,然后将最后一行文字在指定的地方截断,再拼接省略号";
    NSLog(@" %lu ",(unsigned long)context.length);
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10.0f, 60.0f, self.view.frame.size.width - 20.0f, 50.0f)];
    label.font = [UIFont systemFontOfSize:14.0f];
    label.numberOfLines = 2;
    [self.view addSubview:label];
    
    UITapGestureRecognizer *labelTapGestureRecognizer = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(labelTouchUpInside)];
    [label addGestureRecognizer:labelTapGestureRecognizer];
    
    label.text = context;
    [label setReadMoreLabelContentMode];

相关文章

网友评论

      本文标题:iOS UILabel 添加查看更多

      本文链接:https://www.haomeiwen.com/subject/ktosrctx.html