上篇讲了纯代码布局是实现复杂cell的高度计算,下面来说述AutoLayout下cell的高度计算,因为使用了Storyboard布局起来比较简单因此也给cell添加了底部的转发评论bar,先看效果图缓存
因为不少代码与上篇相同,因此这篇主要将cell计算的代码贴出来其余的都同样,自定义cell代码以下ide
// // MTableViewCell.h // cell计算 // // Created by telek on 16/3/14. // Copyright © 2016年 telek. All rights reserved. // #import <UIKit/UIKit.h> @class DataModel; @interface MTableViewCell : UITableViewCell @property (nonatomic, strong) DataModel *model; @end /*************************类的实现****************************/ // // MTableViewCell.m // cell计算 // // Created by telek on 16/3/14. // Copyright © 2016年 telek. All rights reserved. // #import "MTableViewCell.h" #import "UIView+Expand.h" #import "DataModel.h" static CGFloat const margin = 10; @interface MTableViewCell() @property (weak, nonatomic) IBOutlet UIImageView *headIcon; @property (weak, nonatomic) IBOutlet UILabel *nikeName; @property (weak, nonatomic) IBOutlet UILabel *content_text; @property (weak, nonatomic) IBOutlet UIImageView *content_image; @property (weak, nonatomic) IBOutlet UIView *toolbar; @end @implementation MTableViewCell - (void)awakeFromNib { [super awakeFromNib]; self.selectionStyle = UITableViewCellSelectionStyleNone; self.content_text.preferredMaxLayoutWidth = [UIScreen mainScreen].bounds.size.width - 20; } - (void)setFrame:(CGRect)frame { // 使cell之间产生间距 frame = CGRectMake(frame.origin.x, frame.origin.y + margin, frame.size.width, frame.size.height - margin); [super setFrame: frame]; } - (void)setModel:(DataModel *)model { _model = model; // 设置头像 _headIcon.image = [UIImage imageNamed:model.icon]; // 设置用户名 _nikeName.text = model.name; // 设置内容 _content_text.text = model.text; // 强制AutoLayout布局,这样才能拿到准确的高度值 [self layoutIfNeeded]; // 设置图片 if (model.picture) { _content_image.hidden = NO; _content_image.image = [UIImage imageNamed:model.picture]; // cell的高度 = 文字内容的底部 + 图片高度 + 底部toobar的高度 + 3*间距 model.cellHeight = _content_text.bottom + _content_image.height + _toolbar.height + 3 * margin; } else { _content_image.hidden = YES; // cell的高度 = 文字内容的底部 + 底部toobar的高度 + 3*间距 model.cellHeight = _content_text.bottom + _toolbar.height + 3 * margin; } } @end
注释很清楚不用我多作解释,下面我说一下Storyborad中布局时须要注意的的细节布局