如果是iOS8, 那么在storyboard中對cell添加好約束之后只需要再添加兩句代碼就能讓cell自動調整高度
1 self.tableView.estimatedRowHeight = 非0; 2 self.tableView.rowHeight = UITableViewAutomaticDimension;
但是現在大多數應用都還是需要支持iOS7的, 所以在以上基礎上, 再在tableView的代理方法中添加以下即可解決, 在這之前別忘了添加一個屬性
@property (strong, nonatomic) sdTableViewCell *ccll;
並初始化
- (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. _ccll = [self.tableView dequeueReusableCellWithIdentifier:@"cc"];
self.tableView.estimatedRowHeight = 非0;
self.tableView.rowHeight = UITableViewAutomaticDimension;
}
代理方法中:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { sdTableViewCell *cell = (sdTableViewCell *)_ccll; cell.label.text = arr[indexPath.row]; [cell setNeedsUpdateConstraints]; [cell updateConstraintsIfNeeded]; cell.bounds = CGRectMake(0.0f, 0.0f, CGRectGetWidth(tableView.bounds), CGRectGetHeight(cell.bounds)); [cell setNeedsLayout]; [cell layoutIfNeeded]; CGFloat height = [cell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height; NSLog(@"hei%f", height); //加上分割線的1,不然會差一點 return height + 1; }
運行, 就能根據內容自動調整高度了
