iOS 超过一定行数的label强制在末尾加上一个...展开且可以点击成全文

https://segmentfault.com/q/1010000004452279

利用YYText可以解决这个问题 YYLabel.truncationToken

- (void)viewDidLoad {
    
    [super viewDidLoad];

    //代码来自:YYText示例demo

    NSMutableAttributedString *text = [NSMutableAttributedString new];

    UIFont *font = [UIFontsystemFontOfSize:16];

    //添加文本

    NSString *title = @"豫章故郡,洪都新府。星分翼轸,地接衡庐。襟三江而带五湖,控蛮荆而引瓯越。物华天宝,龙光射牛斗之墟;人杰地灵,徐孺下陈蕃之榻。雄州雾列,俊采星驰。台隍枕夷夏之交,宾主尽东南之美。都督阎公之雅望,棨戟遥临;宇文新州之懿范,襜帷暂驻。十旬休假,胜友如云;千里逢迎,高朋满座。腾蛟起凤,孟学士之词宗;紫电青霜,王将军之武库。家君作宰,路出名区;童子何知,躬逢胜饯。时维九月,序属三秋。潦水尽而寒潭清,烟光凝而暮山紫。俨骖騑于上路,访风景于崇阿。临帝子之长洲,得仙人之旧馆。层台耸翠,上出重霄;飞阁流丹,下临无地。鹤汀凫渚,穷岛屿之萦回;桂殿兰宫,列冈峦之体势。";

    [text appendAttributedString:[[NSAttributedString alloc] initWithString:titleattributes:nil]];

    text.yy_font = font ;

    _label = [YYLabel new];

    _label.userInteractionEnabled =YES;

    _label.numberOfLines =0;

    _label.textVerticalAlignment = YYTextVerticalAlignmentTop;

    _label.frame = CGRectMake(60,60, 260,260);

    _label.attributedText = text;

    [self.viewaddSubview:_label];

    _label.layer.borderWidth =0.5;

    _label.layer.borderColor = [UIColorcolorWithRed:0.000green:0.463blue:1.000alpha:1.000].CGColor;

    [selfaddSeeMoreButton];

}

- (void)addSeeMoreButton {

    __weaktypeof(self) _self =self;

    NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithString:@"...more"];

    YYTextHighlight *hi = [YYTextHighlight new];

    [hi setColor:[UIColorcolorWithRed:0.578green:0.790blue:1.000alpha:1.000]];

    hi.tapAction = ^(UIView *containerView,NSAttributedString *text,NSRange range, CGRect rect) {

        YYLabel *label = _self.label;

        [label sizeToFit];

    };

    [text yy_setColor:[UIColorcolorWithRed:0.000green:0.449blue:1.000alpha:1.000]range:[text.stringrangeOfString:@"more"]];

    [text yy_setTextHighlight:hirange:[text.string rangeOfString:@"more"]];

    text.yy_font =_label.font;

    YYLabel *seeMore = [YYLabel new];

    seeMore.attributedText = text;

    [seeMore sizeToFit];

    NSAttributedString *truncationToken = [NSAttributedStringyy_attachmentStringWithContent:seeMorecontentMode:UIViewContentModeCenterattachmentSize:seeMore.frame.sizealignToFont:text.yy_fontalignment:YYTextVerticalAlignmentCenter];

    _label.truncationToken =  truncationToken;

}

Core Text

- (void)drawTextInRect:(CGRect)rect
{
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSaveGState(context);
    //将当前context的坐标系进行flip,否则上下颠倒
    CGAffineTransform flipVertical = CGAffineTransformMake(1,0,0,-1,0,self.bounds.size.height);
    CGContextConcatCTM(context, flipVertical);
    //设置字形变换矩阵为CGAffineTransformIdentity,也就是说每一个字形都不做图形变换
    CGContextSetTextMatrix(context, CGAffineTransformIdentity);
    NSString *attrStr = self.resultAttributedString.string;
    NSRange range = NSMakeRange(0, attrStr.length);
    NSDictionary *dic = [self.resultAttributedString attributesAtIndex:0 effectiveRange:&range];
    NSMutableParagraphStyle *ps =  [dic objectForKey:NSParagraphStyleAttributeName];
    BOOL truncatTail = NO;
    if(ps.lineBreakMode == NSLineBreakByTruncatingTail) {
        truncatTail = YES;
    }
    
    CTFramesetterRef framesetter = [self framesetter];
    CGMutablePathRef pathRef = CGPathCreateMutable();
    CGPathAddRect(pathRef,NULL , CGRectMake(0, 0, self.bounds.size.width, self.bounds.size.height));
     _textFrame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, 0), pathRef,NULL );
    NSInteger numberOfLines = [self numberOfDisplayedLines];
    
    CGSize tempSize = self.frame.size;
    CGSize trueSize = [self getLLLLabelSize];
   
    if (_textFrame) {
        if (numberOfLines > 0 && tempSize.height < trueSize.height) {
            CFArrayRef lines = CTFrameGetLines(_textFrame);
            
            CGPoint lineOrigins[numberOfLines];
            CTFrameGetLineOrigins(_textFrame, CFRangeMake(0, numberOfLines), lineOrigins);
            NSAttributedString *attributedString = self.resultAttributedString;
            for (CFIndex lineIndex = 0; lineIndex < numberOfLines; lineIndex++) {
                CGPoint lineOrigin = lineOrigins[lineIndex];
                CGContextSetTextPosition(context, lineOrigin.x, lineOrigin.y);
                CTLineRef line = CFArrayGetValueAtIndex(lines, lineIndex);
                
                BOOL shouldDrawLine = YES;
                if (lineIndex == numberOfLines - 1 ) {
                    // Does the last line need truncation?
                    CFRange lastLineRange = CTLineGetStringRange(line);
                    if (lastLineRange.location + lastLineRange.length < attributedString.length) {
                        CTLineTruncationType truncationType = kCTLineTruncationEnd;
                        //加省略号的位置
                        NSUInteger truncationAttributePosition = lastLineRange.location + lastLineRange.length - 1;
                        //获取省略号位置的字符串属性
                        NSDictionary *tokenAttributes = [attributedString attributesAtIndex:truncationAttributePosition
                                                                             effectiveRange:NULL];
                        //初始化省略号的属性字符串
                        NSAttributedString *tokenString = [[NSAttributedString alloc] initWithString:kEllipsesCharacter
                                                                                          attributes:tokenAttributes];
                        //创建一行
                        CTLineRef truncationToken = CTLineCreateWithAttributedString((CFAttributedStringRef)tokenString);
                        NSMutableAttributedString *truncationString = [[attributedString attributedSubstringFromRange:NSMakeRange(lastLineRange.location, lastLineRange.length)] mutableCopy];
                        
                        if (lastLineRange.length > 0) {
                            // Remove last token
                            [truncationString deleteCharactersInRange:NSMakeRange(lastLineRange.length - 1, 1)];
                        }
                        [truncationString appendAttributedString:tokenString];
                        
                        //创建省略号的行
                        CTLineRef truncationLine = CTLineCreateWithAttributedString((CFAttributedStringRef)truncationString);
                        // 在省略号行的末尾加上省略号
                        CTLineRef truncatedLine = CTLineCreateTruncatedLine(truncationLine, rect.size.width, truncationType, truncationToken);
                        if (!truncatedLine) {
                            // If the line is not as wide as the truncationToken, truncatedLine is NULL
                            truncatedLine = CFRetain(truncationToken);
                        }
                        CFRelease(truncationLine);//CF得自己释放,ARC的不会释放
                        CFRelease(truncationToken);
                        
                        CTLineDraw(truncatedLine, context);
                        CFRelease(truncatedLine);
                        
                        shouldDrawLine = NO;
                    }
                }
                if(shouldDrawLine) {
                    CTLineDraw(line, context);
                }
            }
        } else {
            CTFrameDraw(_textFrame,context);
        }
    } 
    CGContextRestoreGState(context);
}

你可能感兴趣的:(iOS 超过一定行数的label强制在末尾加上一个...展开且可以点击成全文)