iOS Developer

iOS | CoreText简单实现卷展Label视图

2017-09-13  本文已影响400人  清無

开发背景

需求效果:点击`更多`文本跳转到其他页面 最终效果 - 竖屏 最终效果 - 横屏

实现过程

1.drawRect
-(void)drawRect:(CGRect)rect{
    [super drawRect:rect];
    
    if (!_attributedText) {
        return;
    }
    
    [self drawTextWithCompletion:^(CGFloat height, NSAttributedString *drawAttributedText) {
        [self addSubview:self.contentView];
        self.contentView.frame = CGRectMake(0, 0, self.bounds.size.width, height);
        self.contentView.attributedText = drawAttributedText;
        // 回调
        _action ? _action(HYExpandableLabelActionDidLoad, @(height)) : nil;
    }];
}
2.指定行数绘制
CGRect rect = CGRectMake(0, 0, self.bounds.size.width, .size.height);
CGPathRef path = CGPathCreateWithRect(rect, nil);
CTFramesetterRef setter = CTFramesetterCreateWithAttributedString((CFAttributedStringRef)_attributedText);
CTFrameRef ctFrame = CTFramesetterCreateFrame(setter, CFRangeMake(0, _attributedText.length), path, NULL);
NSArray *lines = (NSArray*)CTFrameGetLines(ctFrame);
CGPoint ctOriginPoints[lines.count];
CTFrameGetLineOrigins(ctFrame, CFRangeMake(0, 0), ctOriginPoints);
NSMutableAttributedString *drawAttributedText = [NSMutableAttributedString new];
    
    for (int i=0; i<lines.count; i++) {
        if (lines.count > _maximumLines && i == _maximumLines) {
            break;
        }
        CTLineRef line = (__bridge CTLineRef)lines[i];
        
        CGPoint lineOrigin = ctOriginPoints[i];
        
        CFRange range = CTLineGetStringRange(line);
        NSAttributedString *subAttr = [_attributedText attributedSubstringFromRange:NSMakeRange(range.location, range.length)];

        if (lines.count > _maximumLines && i == _maximumLines - 1) {
            // 最后一行特殊处理
        }
        else{
            [drawAttributedText appendAttributedString:subAttr];
            
            totalHeight += [self heightForCTLine:line];
        }
    }
NSMutableAttributedString *drawAttr = [[NSMutableAttributedString alloc] initWithAttributedString:subAttr];

for (int j=0; j<drawAttr.length; j++) {
    NSMutableAttributedString *lastLineAttr = [[NSMutableAttributedString alloc] initWithAttributedString:[drawAttr attributedSubstringFromRange:NSMakeRange(0, drawAttr.length-j)]];
    
    [lastLineAttr appendAttributedString:self.clickAttributedText];
    
    NSInteger number = [self numberOfLinesForAttributtedText:lastLineAttr withOriginPoint:lineOrigin];
    // 当满足为一行时,break
    if (number == 1) {
        [drawAttributedText appendAttributedString:lastLineAttr];
        
        CTLineRef moreLine = CTLineCreateWithAttributedString((__bridge CFAttributedStringRef)self.clickAttributedText);
        CGSize moreSize = CTLineGetBoundsWithOptions(moreLine, 0).size;
        // 点击区域
        self.clickArea = CGRectMake(self.bounds.size.width-moreSize.width, totalHeight, moreSize.width, moreSize.height);
        
        totalHeight += [self heightForCTLine:line];
        break;
    }
}
completion(totalHeight, drawAttributedText);
3.全部文本绘制
for (int i=0; i<lines.count; i++) {
        CTLineRef line = (__bridge CTLineRef)lines[i];
        totalHeight += [self heightForCTLine:line];
        // 绘制最后一行时
        if (i == lines.count - 1) {
            CTLineRef moreLine = CTLineCreateWithAttributedString((__bridge CFAttributedStringRef)self.clickAttributedText);
            
// 计算`收起`文本的origin.x值
            NSArray *runs = (NSArray*)CTLineGetGlyphRuns(line);
            CGFloat w = 0;
            for (int i=0; i<runs.count; i++) {
                if (i == runs.count - 1) {
                    break;
                }
                CTRunRef run = (__bridge CTRunRef)runs[i];
                w += CTRunGetTypographicBounds(run, CFRangeMake(0, 0), NULL, NULL, NULL);
            }
            
            CGSize moreSize = CTLineGetBoundsWithOptions(moreLine, 0).size;
            CGFloat h = moreSize.height + lines.count * _lineHeightErrorDimension;
            self.clickArea = CGRectMake(w, totalHeight - h, moreSize.width, h);
        }
    }

用法

@property (weak, nonatomic) IBOutlet HYExpandableLabel *expandableLabel;
// 高度值约束
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *expandableLabelHeightCons;

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _expandableLabel.attributedText = [[NSAttributedString alloc] initWithString:@"测试文本😁"  attributes: @{ NSFontAttributeName:[UIFont systemFontOfSize:14] }];
        
    __block typeof(self)weakSelf = self;
    _expandableLabel.action = ^(HYExpandableLabelActionType type, id info) {
        if (type == HYExpandableLabelActionDidLoad) {
            NSLog(@"_expandableLabel Did Calculated");
// 更新布局
            weakSelf.expandableLabelHeightCons.constant = [info floatValue];
            [weakSelf.view layoutIfNeeded];
        }
    };
}

Github

https://github.com/BackWorld/HYExpandableLabel

如果对你有帮助,别忘了加个关注 或 点个哦😁

上一篇 下一篇

猜你喜欢

热点阅读