美文网首页
label文字显示最多几行,后面添加...更多

label文字显示最多几行,后面添加...更多

作者: guoguojianshu | 来源:发表于2020-09-23 10:42 被阅读0次
 self.XSContentLabel.text = model.dynamicContent;
    NSArray * array = [self XSGetSeparatedLinesFromLabel:self.XSContentLabel];
    NSLog(@"+++%@+++\n%ld",array,array.count);
    if (array.count >3) {
        
        NSString * line3String = array[2];
        NSString * moreString = @"查看全文";
        NSString * showText = [NSString stringWithFormat:@"%@%@%@...%@",array[0],array[1],[line3String substringToIndex:line3String.length - 7],moreString];
        NSLog(@"%@",showText);
        NSMutableAttributedString * attr = [[NSMutableAttributedString alloc]initWithString:showText];
        [attr addAttribute:NSForegroundColorAttributeName  value: [UIColor colorWithHexString:@"#108CFF"] range:NSMakeRange([showText rangeOfString:moreString].location, [showText rangeOfString:moreString].length)];
        self.XSContentLabel.attributedText = attr;
    }
-(NSArray *)XSGetSeparatedLinesFromLabel:(UILabel *)label{
    NSString * text = [label text];
    UIFont * font = [label font];
    CGRect rect = [label frame];
    CTFontRef myfont = CTFontCreateWithName((__bridge CFStringRef)[font fontName], [font pointSize], NULL);
    NSMutableAttributedString * attStr = [[NSMutableAttributedString alloc]initWithString:text];
    [attStr addAttribute:(NSString *)kCTFontAttributeName value:(__bridge id)myfont range:NSMakeRange(0, attStr.length)];
    CTFramesetterRef frameSetter = CTFramesetterCreateWithAttributedString((__bridge CFAttributedStringRef)attStr);
    CGMutablePathRef path = CGPathCreateMutable();
    CGPathAddRect(path, NULL, CGRectMake(0, 0, XS_WIDTH-16*2*XSWIDESCALE, MAXFLOAT));
    CTFrameRef frame = CTFramesetterCreateFrame(frameSetter, CFRangeMake(0, 0), path, NULL);
    
    NSArray * lines = (__bridge 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];
        [linesArray addObject:lineString];
    }
    return linesArray;
}

相关文章

网友评论

      本文标题:label文字显示最多几行,后面添加...更多

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