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

随着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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值