iOS

iOS文本异步渲染(配合YYText)

2018-12-04  本文已影响110人  无敌大闸蟹

关于tableView的性能优化 都是老生常谈 比如frame加载比Auto Layout快 避免cell的高度多次重复计算 滑动时尽量耗时计算提前计算好等等 ·····
当cell的文本内容过多时 我们也可以考虑文本的异步渲染
当显示大量文本时,CPU 的压力会非常大。对此解决方案只有一个,那就是自定义文本控件,用 TextKit 或最底层的 CoreText 对文本异步绘制。尽管这实现起来非常麻烦,但其带来的优势也非常大,CoreText 对象创建好后,能直接获取文本的宽高等信息,避免了多次计算(调整 UILabel 大小时算一遍、UILabel 绘制时内部再算一遍);CoreText 对象占用内存较少,可以缓存下来以备稍后多次渲染。

幸运的是,想支持文本异步渲染也有现成的库 YYText

首先我们的model有个字段是文本显示的内容 model我们叫他TextModel

@interface TextModel : NSObject

@property (nonatomic, strong) NSString *text;

@end

然后构建frameModel

@interface FrameTextModel : NSObject

@property (nonatomic, assign) CGRect titleFrame;

@property (nonatomic, strong) YYTextLayout *titleLayout;

@property (nonatomic, assign) CGFloat cellHeight;

@property (nonatomic, strong) TextModel *textModel;

@end

在textModel的set方法里

- (void)setTextModel:(TextModel *)textModel
{
    _textModel = textModel;
    CGFloat width = [UIScreen mainScreen].bounds.size.width - 20;
    CGFloat bottomSpace = 4;
    NSMutableAttributedString *title = [[NSMutableAttributedString alloc] initWithString:textModel.text];
    title.yy_font = [UIFont systemFontOfSize:16];
    title.yy_color = [UIColor blackColor];
    
    YYTextContainer *titleContainer = [YYTextContainer containerWithSize:CGSizeMake(width, CGFLOAT_MAX)];
    self.titleLayout = [YYTextLayout layoutWithContainer:titleContainer text:title];
    CGSize size = self.titleLayout.textBoundingSize;
    CGFloat titleX = 10;
    CGFloat titleY = 10;
    self.titleFrame = CGRectMake(titleX, titleY, size.width, size.height);
    self.cellHeight = self.titleFrame.size.height + titleY + bottomSpace;
}

这里使用YYTextContainer去构建YYTextLayout 基本思路和计算 frame 类似,只不过把系统的 boundingRectWithSize:、 sizeWithAttributes: 换成 YYText 中的方法
titleFrame是文本的frame大小
cellHeight是cell的高度
然后在cell中实现

- (void)setModel:(FrameTextModel *)model
{
    _model = model;
    self.label.frame = model.titleFrame;
    self.label.textLayout = model.titleLayout;
}

- (YYLabel *)label
{
    if (!_label) {
        _label = [[YYLabel alloc] init];
        _label.displaysAsynchronously = YES;
        _label.ignoreCommonProperties = YES;
        [self.contentView addSubview:_label];
    }
    return _label;
}

displaysAsynchronously要置为yes 开启异步渲染
ignoreCommonProperties是忽略属性
直接赋值frame和textLayout给label即可
看下实际的效果


QQ20181204-133835-HD.gif

我们再用Instruments去看下效果


image.png

fps稳定在60左右

内存在53M左右 后来我用Auto Layout和UILabel配合试了下 大概60M 一样的数据源

上一篇 下一篇

猜你喜欢

热点阅读