cell的自适应高度是根据内容来返回高度,其内容不确定的就是cell上的label的内容,所以归根结底是UILabel根据上面的要显示内容来自适应高度。
自定义UITableViewCell类:MyTableViewCell
定义一个label属性:@property (nonatomic,retain)UILabel *label;
cell的高度就根据label的内容来自适应。
.m文件中代码:
- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
[self drawView];
}
return self;
}
- (void)drawView{
self.label = [[UILabel alloc]init];
self.label.numberOfLines = 0;
[self.contentView addSubview:self.label];
}
在tableView中使用我们自定义的cell:
- (void)viewDidLoad {
[super viewDidLoad];
_str = @"gsulgFJ;FGQASUGHFLWasdin;ASHDPaisdh;AKLSLDJBLlkhjklhjklaksgdlgqiuweASKDH;Alksdhl;AHSF;SdhfjsDHFLASKDFLASHDF";
[self.tableView registerClass:[MyTableViewCell class] forCellReuseIdentifier:@"mycellidentifier"];//这里的重用标识符如果是多人开发的话最好在文件头部用static修饰
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return 3;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
MyTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:myCellID forIndexPath:indexPath];
cell.label.text = _str;
cell.label.frame = CGRectMake(10, 20, 335, [self textHeight:_str]);//label的高度根据内容而定
return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
return [self textHeight:_str] + 30;//调用自适应方法(label高度+30)
}
- (CGFloat)textHeight:(NSString *)str{
NSDictionary *dict = @{NSFontAttributeName:[UIFont systemFontOfSize:17]};
CGRect rect = [str boundingRectWithSize:CGSizeMake(335, 1000) options:NSStringDrawingUsesLineFragmentOrigin attributes:dict context:nil];
return rect.size.height;
}