UITableView介绍 之 AutoLayout下复杂cell的高度计算
上篇讲了纯代码布局是实现复杂cell的高度计算,下面来讲述AutoLayout下cell的高度计算,由于使用了Storyboard布局起来比较简单所以也给cell添加了底部的转发评论bar,先看效果图
由于很多代码与上篇相同,所以这篇主要将cell计算的代码贴出来其他的都一样,自定义cell代码如下
//
// 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中布局时需要注意的的细节
- UILabel设置了lines属性等于0,说明显示多行文字
- 显示多行文字时UILabel的高度约束不要设置
- 底部的头像一行和底部的toolbar基本固定可以设定固定的约束
- 将cell的 identitier的属性设置好,直接可以从缓存中取cell了