
奮斗的郅博
###背景:
在計算cell的實際高度時我們一般是通過計算frame通過拿到最底部一個控件的最大Y值從而得到cell的高度算來算去比較麻煩
其實,iOS8已經(jīng)提供了直接通過Cell高度自適應的方法了,根本不用計算Cell高度,就可以搞定不等高Cell 這個方法即對系統(tǒng)cell有效 也對通多xib創(chuàng)建的cell有效:
具體實現(xiàn)場景
#import "TESTTableViewController.h"
#import "TESTTableViewCell.h"
@interface TESTTableViewController ()
@property (nonatomic,strong) NSArray *contentAry;
@end
@implementation TESTTableViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.tableView.estimatedRowHeight = 100; // 隨便設個不那么離譜的值
self.tableView.rowHeight = UITableViewAutomaticDimension;
self.contentAry = @[@"哈哈哈",@"哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈啊哈哈哈哈哈哈哈哈哈哈哈哈哈啊哈哈哈哈哈哈哈哈哈哈哈哈哈哈啊哈哈哈哈",@"啊哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈啊哈哈哈哈哈",@"哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈啊哈哈哈哈哈哈哈哈哈哈哈哈哈啊哈哈哈哈哈哈哈哈哈哈哈哈哈哈啊哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈啊哈哈哈哈哈哈哈哈哈哈哈哈哈啊哈哈哈哈哈哈哈哈哈哈哈哈哈哈啊哈哈哈哈"];
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return 4;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *ID = @"cell";
//利用系統(tǒng)自帶cell類型
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
}
cell.textLabel.numberOfLines = 0;
cell.textLabel.text = self.contentAry[indexPath.row];
return cell;
}
@end

實現(xiàn)效果圖
小結:
設置tableView的估算Cell高度和rowHeight值為自動計算模式(具體實現(xiàn)原理)
self.tableView.estimatedRowHeight = 100; // 隨便設個不那么離譜的值
self.tableView.rowHeight = UITableViewAutomaticDimension;