第一步:创建ExampleTableViewCell类
-(instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString*)reuseIdentifier{
self= [superinitWithStyle:stylereuseIdentifier:reuseIdentifier];
if(self) {
_onlyLabel= ({
UILabel*view = [UILabelnew];
[self.contentViewaddSubview:view];
[viewmas_makeConstraints:^(MASConstraintMaker*make) {
make.left.right.equalTo(self);
}];
view.numberOfLines=0;
view.font= [UIFontsystemFontOfSize:15];
view;
});
}
returnself;
}
第二步:将需要动态调节的Cell设置为属性
@interfaceGoodsViewController()<
UITableViewDelegate,
UITableViewDataSource
>
@property(nonatomic,strong)ExampleTableViewCell *exampleCell;
@end
第三步:通过sizeToFit更新cell内控件在刷新后的frame,然后将更新后的空间的height赋值给cell
-(UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath{
_exampleCell= [tableView dequeueReusableCellWithIdentifier:@"exampleCell"];
_exampleCell.onlyLabel.text= @"someText";
[_exampleCell.onlyLabel sizeToFit];
NSLog(@"%f",_exampleCell.onlyLabel.bounds.size.height);
CGRectcellFrame =_exampleCell.frame;
cellFrame.size.height=_exampleCell.onlyLabel.bounds.size.height;
[_exampleCell setFrame:cellFrame];
return _exampleCell;
}
第四步:返回更新后的height
-(CGFloat)tableView:(UITableView*)tableView heightForRowAtIndexPath:(NSIndexPath*)indexPath{
return _exampleCell.frame.size.height;
}
如有更好的方法还希望大家可以互相交流
网友评论