一直感觉高深莫测的Cell自适应行高,终于搞明白了他内在的奥秘。
最初小伙伴们告诉我有第三方链接地址:点击打开链接 但是我这个人比较奇怪,犟脾气上来以后飞得自己写!于是就用原生的Autolayout写了一下。
大概思路是这样的:
1、自定义一个cell,关键点在于你布局控件上面,内容部分不能固定它的高度,在布局的时候固定好上、左、下、右就OK了。
代码如下:
NSLayoutConstraint *constraint = [NSLayoutConstraint constraintWithItem:self.contentView attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:self.contentLabel attribute:NSLayoutAttributeHeight multiplier:1.0 constant:20];
constraint.priority = UILayoutPriorityDefaultLow;
constraint.active = YES;
[NSLayoutConstraint activateConstraints:@[
//上
[NSLayoutConstraint constraintWithItem:self.contentLabel attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.contentView attribute:NSLayoutAttributeTop multiplier:1.0 constant:5],
//左
[NSLayoutConstraint constraintWithItem:self.contentLabel attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self.contentView attribute:NSLayoutAttributeLeft multiplier:1.0 constant:10],
//下
[NSLayoutConstraint constraintWithItem:self.contentLabel attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self.contentView attribute:NSLayoutAttributeBottom multiplier:1.0 constant:-10],
//右
[NSLayoutConstraint constraintWithItem:self.contentLabel attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:self.contentView attribute:NSLayoutAttributeRight multiplier:1.0 constant:-10]]];
2、实现tableView的两个代理方法 代码如下:
- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 66;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return UITableViewAutomaticDimension;
}
3、接下来正常的操作就行了 还有问题不会的资讯QQ:954895928