如何在UILabel的内容较多时只显示3行的内容,在省略号后显示更多,点击更多添加点击的动作

如上述要求,我们可以给UILabel 添加一个类别方法,
@interface UILabel (ReadMore)

-(void)setReadMoreLabelContentMode;

@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 = 7; // 截取的长度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:16.0f],

                                       NSForegroundColorAttributeName : [UIColor blueColor]

                                       } range:NSMakeRange(contentText.length, 4)];

    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

调用该方法的的代码:

- (void)viewDidLoad {

    [super viewDidLoad];

    

    NSString *context = @"当最后一行显示不全时,需求有时候需要改变省略号的位置,系统并未提供,张娜拉邀请我去她家里玩了一会,然后吃饭,看电视动词打次,然后将最后一行文字在指定的地方截断,再拼接省略号";

        NSLog(@" %lu ",(unsigned long)context.length);

        

        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10.0f, 60.0f, self.view.frame.size.width - 20.0f, 70.0f)];

        label.font = [UIFont systemFontOfSize:16.0f];

        label.numberOfLines = 3;

        [self.view addSubview:label];

        

        UITapGestureRecognizer *labelTapGestureRecognizer = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(labelTouchUpInside)];

        [label addGestureRecognizer:labelTapGestureRecognizer];

        

        label.text = context;

        [label setReadMoreLabelContentMode];

}

-(void)labelTouchUpInside{

    NSLog(@"查看更多");

}

猜你喜欢

转载自blog.csdn.net/u013712343/article/details/135106623