iOS xib布局自适应高度的TableViewCell

除开对这种方式的热衷,我觉的更多的是自己变的懒惰,但是我们的宗旨不变,写最少的代码做更多的事。

在布局之前,先认识下本篇的关键字“UITableViewAutomaticDimension”,这个关键字说明文档是这样介绍的:

// Returning this value from tableView:heightForHeaderInSection: or tableView:heightForFooterInSection: results in a height that fits the value returned from

// tableView:titleForHeaderInSection: or tableView:titleForFooterInSection: if the title is not nil.

UIKIT_EXTERN const CGFloat UITableViewAutomaticDimension API_AVAILABLE(ios(5.0));

貌似说的是SectionHeader/Footer(表头/尾)高度返回的值,压根没提到rowHeight,更没estimatedRowHeight的什么事,没关系咱继续往下。

一、Command+N新建继承自UITableViewCell的类,并绑定xib文件,拖拉控件及布局约束

        接着模仿聊天泡泡来布局Cell,一个头像,一个泡泡。布局的关键在于添加约束条件,就是各种拉线拖拖拖或者傻瓜式点点点。

        给头像视图添加上、左边距、宽及宽高比布局约束

头像视图

        添加泡泡视图及泡泡文本视图,并添加泡泡视图布局约束及泡泡文本视图约束(重点)

拉线布局

        泡泡视图添加约束效果:

重点在右边距

        泡泡文本视图添加约束:

        将文本Label设置成cell的属性变量,用于代码动态赋值text内容:

        #import

        NS_ASSUME_NONNULL_BEGIN

        @interface SimpleAutomaticCell : UITableViewCell

        @property (weak, nonatomic) IBOutlet UILabel *contentLab;//label属性变量

        @property (strong, nonatomic) NSString *content;

        @end

        NS_ASSUME_NONNULL_END

        @implementation SimpleAutomaticCell

        - (void)awakeFromNib {

            [super awakeFromNib];

            // Initialization code

        }

        - (void)setContent:(NSString*)content {

            _content = content;

            self.contentLab.text = content;//动态赋值text内容

        }

        @end

二、Command+N新建ViewController视图控制器,并绑定xib文件,拖拽UITableView控件到视图控制器,拖拉进行布局约束,并将UITableView设置为属性变量,xib中设置表视图的RowHeight和Estimate为Automatic(关键设置)

设置关键属性值

三、编写Cell注册代码,实现UITableView相关代理方法,不需要实现- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{}代理方法

注册Cell
实现代理方法

四,最后运行看效果

模仿聊天效果

以上只是简单的单元格样式,依此类推包括复杂的视图布局,也可以最少的代码来得以实现,那么问题来了,如果在xib设置中没有勾选RowHeight和Estimate为Automatic,是否可以用代码代替,答案是当然可以,回到开头提到的关键字“UITableViewAutomaticDimension”,这个就是答案

未选择Automatic

使用代码替代xib参数配置方式有两种:

        方式一:设置UITableView的属性值(rowHeight、estimatedRowHeight),必须两个属性都赋值

        self.mainTableView.rowHeight = UITableViewAutomaticDimension;

        self.mainTableView.estimatedRowHeight = UITableViewAutomaticDimension;

属性赋值方式

        方式二:实现UITableView的相关代理方法(heightForRowAtIndexPath、estimatedHeightForRowAtIndexPath),必须两个代理方法都实现

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

            return UITableViewAutomaticDimension;

        }

        - (CGFloat)tableView:(UITableView *)tableView  estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath{

            return UITableViewAutomaticDimension;

        }

代理方式

所以你GET到了吗?

▶︎欢迎查阅◀︎

最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容