Dynamic UITableViewCell in autolayout
參考這裡
客製化一個 UITableViewCell 並設定好 Autolayout constraints
以這個例子來說, 客製化一個 Cell 高度依照裡面的 UILabel 高而改變
注意: UILabel 的 numberOfLines 要設為 0
在 ViewDidLoad 註冊這個 Cell
- (void)viewDidLoad
{
[super viewDidLoad];
UINib *cellNib = [UINib nibWithNibName:@"MyCell" bundle:nil];
[self.tableView registerNib:cellNib forCellReuseIdentifier:@"MyCell"];
}
定義一個 method, 返回所需的客製化 Cell
- (MyCell *)cellForTableView:(UITableView *)tableView AtIndexPath:(NSIndexPath *)indexPath
{
MyCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyCell"];
if(indexPath.row %2 == 0)
{
cell.title.text = @"Hello World";
}
else
{
cell.title.text = @"Hello World, Hello World, Hello World, Hello World, Hello Word2";
}
return cell;
}
在 UITableViewDelegate return Cell height 設置為:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
MyCell *cell = [self cellForTableView:tableView AtIndexPath:indexPath];
[cell.contentView setNeedsLayout];
[cell.contentView layoutIfNeeded];
CGSize size = [cell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
// why add 1, because size is cell.contentView' size
return size.height + 1;
}
在 UITableViewDataSource return Cell 設置為:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
return [self cellForTableView:tableView AtIndexPath:indexPath];
}