UITableViewCell使用自动布局的“最佳实践”

前言

iOS 处理TableView的复杂Cell是一件很麻烦的事情,我们得计算Cell里面内容的Frame以及Cell的高度,现在有一种相对高效的方式,使用自动布局的Cell可以让这件事变得容易起来了,不用再去计算里面的Frame和自身的高度,接下来谈论下这种方式的实现以及里面的坑。

实战

我们实现了一个这样的UITableView:
自动布局Cell的TableView
这是一个简单的列表,和其他的列表无异,不过Cell里面的布局使用了是自动布局。

  • 首先需要设置UITableVIew的自动布局相关的属性
    self.tableView.estimatedRowHeight = 200;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
  • 然后重写UITableVIew的delegate和DataSource方法

这里不需要再重写返回cell高度的方法了,因为使用了自动布局的Cell,Cell的高度有Cell的内容来决定就好了。

#pragma mark - ......::::::: UITableViewDelegate :::::::......

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _datas.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    AutolayoutCell* cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([AutolayoutCell class])];
    GameModel* gameModel = _datas[indexPath.row];
    [cell loadData:gameModel indexPath:indexPath];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    UITableViewCell* cell = [tableView cellForRowAtIndexPath:indexPath];
    [TagViewUtils showTaggingViewWithView:cell.contentView];
}
  • 接下来就是Cell的实现了

自动布局的框架使用的是Masonry,自动布局的Cell基本的思想就是让Cell里面的内容决定Cell的高度,所以除了常规的设置元素的约束之外,还需要一个到父View底部的约束,这样父View才会根据子View的内容计算出自身的高度。特别地,需要给最后设置的这个约束添加上一个优先级的值,可以设置为是一个小于1000的值,这里设置的是900,因为iOS计算高度会有点小的偏差,是一个很小的小数值,在运行的时候会出现类似的警告信息:

2017-05-28 00:04:31.751783+0800 AutolayoutCell[27341:18908463] [LayoutConstraints] Unable to simultaneously satisfy constraints.
	Probably at least one of the constraints in the following list is one you don't want. 
	Try this: 
		(1) look at each constraint and try to figure out which you don't expect; 
		(2) find the code that added the unwanted constraint or constraints and fix it. 
(
    "<MASLayoutConstraint:0x6000000b7c40 UIImageView:0x7ff9afd1a1f0.top == UITableViewCellContentView:0x7ff9afd199b0.top + 9.03333>",
    "<MASLayoutConstraint:0x6000000b7d00 UIImageView:0x7ff9afd1a1f0.bottom == UITableViewCellContentView:0x7ff9afd199b0.bottom - 9>",
    "<MASLayoutConstraint:0x6000000b7ee0 UIImageView:0x7ff9afd1a1f0.height == 61>",
    "<NSLayoutConstraint:0x618000091a80 UITableViewCellContentView:0x7ff9afd199b0.height == 79>"
)

Will attempt to recover by breaking constraint 
<MASLayoutConstraint:0x6000000b7ee0 UIImageView:0x7ff9afd1a1f0.height == 61>

可以通过设置最终决定父View高度的子View到父View底部的约束的优先级来解决这个问题。

    [gameIconImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.contentView).offset(84.0/3);
        make.top.equalTo(self.contentView).offset(27.1/3);
        make.bottom.equalTo(self.contentView).offset(-27.1/3);
        make.width.equalTo(@(183.0/3));
        // 设置优先级处理警告信息
        make.height.equalTo(@(183.0/3)).priority(900);
    }];

完整的Cell代码实现


#import "AutolayoutCell.h"
#import <Masonry.h>
#import "GameModel.h"
#import <UIImageView+WebCache.h>

@interface AutolayoutCell () {
    GameModel* _gameModel;
}

@property (nonatomic, weak) UIImageView* gameIconImageView;
@property (nonatomic, weak) UILabel* gameTitleLabel;
@property (nonatomic, weak) UILabel* gameTagLabel;
@property (nonatomic, weak) UILabel* gameRateLabel;

@end

@implementation AutolayoutCell

- (instancetype)init {
    self = [super init];
    if (self) {
        [self myInit];
    }
    return self;
}

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        [self myInit];
    }
    return self;
}

- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];
}

- (void)myInit {
    UIImageView* gameIconImageView = [UIImageView new];
    gameIconImageView.backgroundColor = [UIColor redColor];
    gameIconImageView.contentMode = UIViewContentModeScaleAspectFill;
    gameIconImageView.layer.cornerRadius = 5;
    gameIconImageView.layer.masksToBounds = YES;
    [self.contentView addSubview:gameIconImageView];
    [gameIconImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.contentView).offset(84.1/3);
        make.top.equalTo(self.contentView).offset(27.1/3);
        make.bottom.equalTo(self.contentView).offset(-27.0/3);
        make.width.equalTo(@(183.0/3));
        make.height.equalTo(@(183.0/3)).priority(900);
    }];
    _gameIconImageView = gameIconImageView;
    
    
    UILabel* gameRateLabel = [UILabel new];
    gameRateLabel.numberOfLines = 1;
    gameRateLabel.text = @"9.3";
    gameRateLabel.textColor = [UIColor redColor];
    gameRateLabel.font = [UIFont systemFontOfSize:24];
    [self.contentView addSubview:gameRateLabel];
    _gameRateLabel = gameRateLabel;
    [_gameRateLabel setContentHuggingPriority:UILayoutPriorityDefaultHigh forAxis:UILayoutConstraintAxisHorizontal];
    [_gameRateLabel setContentCompressionResistancePriority:UILayoutPriorityDefaultHigh forAxis:UILayoutConstraintAxisHorizontal];
    [gameRateLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.contentView).offset(-78.0/3);
        make.top.equalTo(self.contentView).offset(45.0/3);
    }];
    
    
    UILabel* gameTitleLabel = [UILabel new];
    gameTitleLabel.numberOfLines = 1;
    gameTitleLabel.text = @"Star Trek Star Trek Star Trek Star Trek Star Trek ";
    gameTitleLabel.font = [UIFont systemFontOfSize:16];
    gameTitleLabel.textColor = [UIColor blackColor];
    [self.contentView addSubview:gameTitleLabel];
    _gameTitleLabel = gameTitleLabel;
    [_gameTitleLabel setContentHuggingPriority:UILayoutPriorityDefaultLow forAxis:UILayoutConstraintAxisHorizontal];
    [_gameTitleLabel setContentCompressionResistancePriority:UILayoutPriorityDefaultLow forAxis:UILayoutConstraintAxisHorizontal];
    [gameTitleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_gameIconImageView.mas_right).offset(48.0/3);
        make.top.equalTo(_gameIconImageView).offset(21.0/3);
        make.right.equalTo(_gameRateLabel.mas_left).offset(-55.0/3);
    }];
    
    UILabel* gameTagLabel = [UILabel new];
    gameTagLabel.numberOfLines = 1;
    gameTagLabel.text = @"Category:MMOPRG";
    gameTagLabel.font = [UIFont systemFontOfSize:14];
    gameTagLabel.textColor = [UIColor lightGrayColor];
    [self.contentView addSubview:gameTagLabel];
    _gameTagLabel = gameTagLabel;
    [_gameTagLabel setContentHuggingPriority:UILayoutPriorityDefaultHigh forAxis:UILayoutConstraintAxisHorizontal];
    [gameTagLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_gameIconImageView.mas_right).offset(48.0/3);
        make.bottom.equalTo(_gameIconImageView).offset(-21.0/3);
    }];
    
    UIView* sepLine = [UIView new];
    sepLine.backgroundColor = [UIColor lightGrayColor];
    [self.contentView addSubview:sepLine];
    [sepLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.contentView).offset(54.0/3);
        make.right.equalTo(self.contentView).offset(-54.0/3);
        make.bottom.equalTo(self.contentView);
        make.height.equalTo(@(1));
    }];
    
    
//    gameTagLabel.alpha = 0;
//    gameRateLabel.alpha = 0;
}

- (void)loadData:(id)data indexPath:(NSIndexPath *)indexPath {
    if ([data isKindOfClass:[GameModel class]]) {
        _gameModel = data;
        
        [_gameIconImageView sd_setImageWithURL:[NSURL URLWithString:_gameModel.image]];
        _gameTitleLabel.text = _gameModel.name;
        _gameTagLabel.text = [NSString stringWithFormat:@"%@:%@", @"Category", _gameModel.category];
        _gameRateLabel.text = [NSString stringWithFormat:@"%@", @(_gameModel.point)];
    }
}

@end
注意点
setContentHuggingPriority和setContentCompressionResistancePriority的使用

以这个图为例

自动布局Cell的TableView

右边的数字和坐标的标题宽度都是动态数据决定的,在这个场景中,我们需要实现的是这样的效果:数字的优先级比较高,数字需要完全被展示,不能被压缩,而标题当内容超过边界值,需要被截取。
从压缩内容角度来看: 当标题的文字超过了数字,被压缩的应该是标题,可以查看第二个Cell的例子。因此数字的防止压缩的优先级比标题的高,可以通过setContentCompressionResistancePriority方法,设置数字更大的防止压缩优先级来达到效果
**从拉伸角度来看:**如果不改变对默认的其方式,希望数字能够一直停留在左边,那么当标题没有超过边界值,有一者是需要被拉伸的,如果是数字被拉伸,那么默认的对其方式就不会实现数字停留在最左边的效果了,所以可以通过设置拉伸的优先级来达到效果,通过setContentHuggingPriority来设置数字比较小的优先级实现。

    [_gameRateLabel setContentHuggingPriority:UILayoutPriorityDefaultHigh forAxis:UILayoutConstraintAxisHorizontal];
    [_gameRateLabel setContentCompressionResistancePriority:UILayoutPriorityDefaultHigh forAxis:UILayoutConstraintAxisHorizontal];

    [_gameTitleLabel setContentHuggingPriority:UILayoutPriorityDefaultLow forAxis:UILayoutConstraintAxisHorizontal];
    [_gameTitleLabel setContentCompressionResistancePriority:UILayoutPriorityDefaultLow forAxis:UILayoutConstraintAxisHorizontal];
总结

使用自动布局的Cell在一定的程度上提高了开发效率,不过需要注意自动布局中的某些坑,才能让自动布局更好的工作。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值