- 前言:自適應高度的處理有如下:
1.使用系統(tǒng)提供方法
2.使用第三方+XIB(AutoLayout)
3.使用第三方+Masonry(純代碼)
- 框架下載:
Masonry
UITableView+FDTemplateLayoutCell - 本文基于第三方框架UITableView+FDTemplateLayoutCell配合Masonry使用進行簡要講解,如果需要配合Xib進行使用的,請參閱如下文章:
1.導入文件
Paste_Image.png
2.在viewDidLoad打開開關和注冊
Paste_Image.png
- (void)viewDidLoad {
[super viewDidLoad];
[self AccessNetworkForDateMethod];
self.view.backgroundColor = [UIColor lightGrayColor];
self.ZTableView = [[UITableView alloc]initWithFrame:[UIScreen mainScreen].bounds];
self.ZTableView.delegate = self;
self.ZTableView.dataSource =self;
[self.view addSubview:self.ZTableView];
#warning log日志是否輸出
self.ZTableView.fd_debugLogEnabled = YES;
#warning 注冊Cell類,無論是純代碼的Cell,還是Xib的cell,否則會報錯
[self.ZTableView registerClass:[ZTableViewCell class] forCellReuseIdentifier:@"myCell"];
}
3.在返回高度方法中預緩存高度值
Paste_Image.png
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
#warning 預緩存高度
return [self.ZTableView fd_heightForCellWithIdentifier:@"myCell" cacheByKey:indexPath configuration:^(ZTableViewCell *cell) {
cell.cellModel = self.listArry[indexPath.row];
}];
// [self.ZTableView fd_heightForCellWithIdentifier:@"myCell" cacheByKey:indexPath configuration:^(id cell) {
// }];
}
4.自定義Cell類注意
Paste_Image.png
-(void)initCell{
self.sumLab = [[UILabel alloc]init];
#warning 所有的控件都是放置在"self.contentView"
[self.contentView addSubview:self.sumLab];
self.sumLab.text =@"測試階段";
#warning Lable行數限制設為0
self.sumLab.numberOfLines = 0;
#warning 使用Masonry設置高度大小位置,無論如何,基于Bottom這個點是不能忽略的,位置也都是基于self.contentView
[self.sumLab mas_makeConstraints:^(MASConstraintMaker *make) {
make.top.mas_equalTo(self.contentView.mas_top).offset(5);
make.left.mas_equalTo(self.contentView.mas_left).offset(5);
make.right.mas_equalTo(self.contentView.mas_right).offset(-5);
make.bottom.mas_equalTo(self.contentView.mas_bottom).offset(-5);
}];
}
運行效果如下:
非代碼挖坑注意:
如果發(fā)現代碼運行在不同Xcode版本上,發(fā)現高度無法自適應,請?zhí)鎿Q最新的UITableView+FDTemplateLayoutCell框架,就能修正此問題.
demo下載:
https://github.com/OwenJoe/cellHeight.git
挖坑過程碰到很多問題,參閱文章如下:
http://blog.sunnyxx.com/2015/05/17/cell-height-calculation/
http://www.reibang.com/p/385e0bfebba2
http://www.reibang.com/p/ca11e0e07de4