美文网首页
iOS Cell文字自适应的两种方案 (二)

iOS Cell文字自适应的两种方案 (二)

作者: 翻滚的炒勺2013 | 来源:发表于2017-09-16 14:43 被阅读127次
白百何.jpg

先看效果

Untitled.gif

图中的自适应是利用Masonry结合iOS 8 以后苹果提供的estimatedRowHeight实现自动计算行高,简单方便适应只有文字需要动态计算的情况

0.打开预估行高属性

        _tableView.estimatedRowHeight = 100;

说明:100是这里的预估高度并不是真实的高度,每次tableView在滑动的时候会以预估行高为参考值进行计算,苹果官方文档说这个值越接近真实的高度,计算的高度越准确

1.设置label

- (UILabel *)contentLabel {
    if (_contentLabel == nil) {
        _contentLabel = [[UILabel alloc]init];
        _contentLabel.text = @"内容";
        _contentLabel.font = [UIFont systemFontOfSize:13];
        _contentLabel.numberOfLines = 0;
        _contentLabel.textAlignment = NSTextAlignmentLeft;
        _contentLabel.textColor = [UIColor darkGrayColor];
    }
    return _contentLabel;
}

说明: _contentLabel.numberOfLines = 0;一定不要忘记打开,否则不会折行显示

3.最后设置label的frame ,这里我用的是Masonry布局

    /// 添加头像
    [self addSubview:self.icon];
    [self.icon mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.mas_equalTo(self).offset(space);
        make.size.mas_equalTo(CGSizeMake(space * 2, space * 2));
    }];
    
    /// 添加内容
    [self addSubview:self.contentLabel];
    [self.contentLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.icon);
        make.right.mas_equalTo(self).offset(-space);
        make.top.mas_equalTo(self.icon.mas_bottom).offset(space);
    }];
    
    /// 点赞按钮
    [self addSubview:self.dicsucButton];
    [self.dicsucButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.contentLabel.mas_bottom).offset(space);
        make.right.mas_equalTo(self).offset(-space);
        make.bottom.equalTo(self).offset(-5);
    }];
C727C3D3-16B9-4E19-BDE7-9870936B0021.png

说明:他们的位置关系我已经在图上画出,,label的高度是根据里面的内容自动撑开的,所以不用设置label底部的约束

相关文章

网友评论

      本文标题:iOS Cell文字自适应的两种方案 (二)

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