iOS8 UITableView動態加載cell的高度
iOS8新特性,ios8以後,你在也不需要根據cell上內容的不一樣計算每個cell的高度了,因爲系統可以自己加載它的高度。下面是具體的實現代碼:
@interface ViewController ()<UITableViewDataSource,UITableViewDelegate>
// 數據源
@property (nonatomic, strong) NSMutableArray *dataArray;
@end
@implementation ViewController
[super viewDidLoad];
// 設置一個默認的值
_tableView.rowHeight = UITableViewAutomaticDimension;
// 這個高度可以隨便設置,可以是 44 或者其他數
_tableView.estimatedRowHeight = 4;
_dataArray =[NSMutableArray arrayWithCapacity:0] ;
[_dataArray addObjectsFromArray:@[@"1",@"2",@"3",@"了一個激動人心的特性,UITableView 的 Self Sizing Cells。對於開發者來",@"在iOS8中,蘋果給出了一個激動人心的特性,UITableView 的 Self Sizing Cells。對於開發者來說,這是一個很值得一試的特性,在iOS8以前,如果需要在UITableViewCell中展示動態的內容,必須每次計算內容所佔高度,然後賦值給UITableView的height。在iOS8中,蘋果給出了一個激動人心的特性,UITableView 的 Self Sizing Cells。對於開發者來說,這是一個很值得一試的特性,在iOS8以前,如果需要在UITableViewCell中展示動態的內容,必須每次計算內容所佔高度,然後賦值給UITableView的height。"]];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return _dataArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *identifier = @"ID";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
}
cell.textLabel.text = _dataArray[indexPath.row];
cell.textLabel.numberOfLines = 0;
return cell;
}
運行結果:高度系統自動幫算好了