实现UITabelView自适应高度的几点注意事项

我们设置单元格高度的时候

有固定高度的情况,通过:

self.tableView.rowHeight=88;
也可以设置datasource中
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {}
实现了这个方法后,rowHeight的设置将无效。

我们平时用到的UITableView  让其自动适应高度 我们可以

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {}

这个数据源代理方法中实现 

UITableViewAutomaticDimension

这种方法  但这个方法一般情况下可以。

 

下面我想说一下 我经常使用的方法 就是用SDAutoLayout的布局三方

SDAutoLayout有很详细的UITableView的各种好的方法 这里我们可义参考SDAutoLayout的官方Demo 里面有很详细的参考代码

这里就不重复了  github上搜索SDAutoLayout就可下载Demo

 

首先就是在自定义的各种单元个里 设置好各个空间的frame之后 在

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier 

这个方法里设置

 

提到这个方法 我还想多补充一句 就是曾经忽视导致遇到的坑 很久没有解决 就是在重写cell的时候 无法显示子控件 然后断点调试查看发现初始化方法没有走

并且一直看不清 原来是写成了- (instancetype)initWithFrame 这个方法 没有很注意区分就这样跳进了一个坑  而且并不会很清楚地注意到这一点 

 

好了 言归正传 就是在这个方法里添加号控件之后 加一句  上代码

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        self.backgroundColor = [UIColor colorWithWhite:0.1 alpha:1];
        [self.contentView addSubview:self.tagsView];
        [self.contentView addSubview:self.editBtn];
       
       // sd适配子控件 按钮方法 self.editBtn.sd_layout.rightSpaceToView(self.contentView,10).centerYIs(self.tagsView.height/2).heightIs(kWidthScale(30)).widthIs(kWidthScale(30));
        [self setupAutoHeightWithBottomView:self.tagsView bottomMargin:5];
        
    }
    return self;
}

 

[self setupAutoHeightWithBottomView:self.tagsView bottomMargin:5];注意是这一句
然后在viewController里面的tableView的rowHeight代理方法里面

return [self.tableV cellHeightForIndexPath:indexPath model:nil keyPath:nil cellClass:[MineOneTableViewCell class] contentViewWidth: [UIScreen mainScreen].bounds.size.width];

返回这个  model这里为nil  到时候传递需要的额model即可

 

但是 这个方法有时候会遇到问题 就是当单元格很多并且自适应cell高度 然后表格高度计算的时候 其实会有计算不出rowheight的问题  具体原因以后总结 

但是最好的方法 目前找到的就是

[self.tableV cellHeightForIndexPath:indexPath cellClass:[MineOneTableViewCell class] cellContentViewWidth:kScreenWidth cellDataSetting:nil];使用这个方法来返回单元格的高度

这里可以使用注册的方式创建cell  这样基本无论cell也可以自适应子控件高度了 而且 tableView的rowHeight也可以完全自适应不用的自定义cell的样式的各种高度

反正使用很多次觉得这个很好用  SDAutoLayout还提供了很多方法 慢慢总结上传

 

posted @ 2017-02-16 23:19  wangxiaoqi  阅读(1928)  评论(0编辑  收藏  举报