懒加载和Masonry结合

    xiaoxiao2021-03-25  145

    最近优化自己的项目,把一些控件多的列表页改为了懒加载,结合一直使用的Masonry纯代码适配,特地总结一下。

    懒加载,就是到用到它的时候他才会进行初始化,而且只初始化一次,尤其在一些控件较多的列表页,可以很好的优化性能,缓解UITableView的滑动掉帧问题。下面举一个在UITableViewCell中懒加载控件的例子。

    首先,先声明一个控件属性

    @property (nonatomic,strong) UILabel *titlel; 然后是懒加载的使用 -(UILabel *)titlel { if(!_titlel) { _titlel = [UILabel new]; _titlel.font = [UIFont systemFontOfSize:14]; _titlel.numberOfLines = 0; } return _titlel; }//在重载getter方法中,不可以使用self.来引用控件,否则会造成死循环 最后在cell初始化的方法里把控件添加到cell上并用Masonry创建约束 -(id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier { self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]; if(self) { [self addSubview:self.titlel];//注意!这里一定要用self.引用控件,否则会无法显示 [_titlel mas_makeConstraints:^(MASConstraintMaker *make) { make.left.equalTo(self.mas_left).offset(10); make.centerY.equalTo(self.mas_centerY); make.right.equalTo(self.mas_right).offset(-10); }]; } return self; } 到这里控件算是走完了懒加载的流程。
    转载请注明原文地址: https://ju.6miu.com/read-13023.html

    最新回复(0)