iOS UITableView Cell动态高度(使用AutoLayout)

来源:互联网 发布:东北经济振兴 知乎 编辑:程序博客网 时间:2024/05/23 00:01

随着autoLayout使用的增多,开发者越发的希望cell可以根据内容自动计算高度.

为了能够尽量方便的使用,以及代码规范的要求,本人封装了一个Manager类,这个manager持有一个cell,且根据cell的数据,估算cell的高度并返回,使用时,只需要实现几个代理方法,就可以了.

github:https://github.com/YanChen-ing/CellDynamicHeightManager.git


下面上代码:

YCICellDynamicHeightManager.h

@protocol YCICellDynamicHeightManagerDelegate <NSObject>@required//配置宽度- (void)setUpPreferredWidth;//根据model刷新UI- (void)bindDataWithModel:(NSObject *)model;//保存/获取高度信息,建议保存在model中- (void)saveCellHeight:(CGFloat)height;- (CGFloat)getCellHeight;@end/** 仅支持autolayout布局的cell,必须遵守<YCICellDynamicHeightManagerDelegate> */@interface YCICellDynamicHeightManager : NSObject/** *  注: cell必须遵守协议<YCICellDynamicHeightManagerDelegate> */- (instancetype)initWithCellClass:(Class)aClass;- (instancetype)initWithCell:(UITableViewCell<YCICellDynamicHeightManagerDelegate> *)aCell;/** *  计算高度,已包含对 获取/存储 高度信息的处理 */- (CGFloat)cellHeightWithModel:(NSObject *)model;@end


使用:

1.在自己的cell类遵守<YCICellDynamicHeightManagerDelegate>并实现其方法.

2.viewController中创建manager,并通过自定义的初始化器创建.

//创建一个Manager    _dynamicManager = [[YCICellDynamicHeightManager alloc]initWithCellClass:[YCIDynamicCell class]];

3.在tableView:heightForRowAtIndexPath中,调用cellHeightWithModel:方法.

<span style="font-size:18px;">- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{    //用manager 测量高度    YCIDynamicModel *model = _models[indexPath.row];    return [_dynamicManager cellHeightWithModel:model];}</span>



0 0