开发中经常会遇到需要动态调整UITableViewCell的高度的问题,这个问题百度到的十分不清楚,但是谷歌到的就十分清楚,在百度没完之前我还是自己还是记录下吧……
方法一:使用AutoLayout
在storyboard中设置label的约束如图所示:
或者:
然后在viewDidLoad中添加
1 2
| self.tableView.rowHeight = UITableViewAutomaticDimension; self.tableView.estimatedRowHeight = 44;
|
tableView需要设置为Dynamic Prototypes,上图的约束一条都不能少!!
方法二:调用heightForRowAtIndexPath
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| #define ScreenFrame [[UIScreen mainScreen]bounds] #define ScreenSize ScreenFrame.size #define FONT_SIZE 15.0f #define CELL_CONTENT_WIDTH ScreenSize.width #define CELL_CONTENT_MARGIN 8.0f
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
NSDictionary *rowData = _dataArray[indexPath.section]; text = [rowData objectForKey:@"content"];
CGSize constraint = CGSizeMake(CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 2), 20000.0f); NSAttributedString *attributedText = [[NSAttributedString alloc]initWithString:text attributes:@{ NSFontAttributeName:[UIFont systemFontOfSize:FONT_SIZE] }]; CGRect rect = [attributedText boundingRectWithSize:constraint options:NSStringDrawingUsesLineFragmentOrigin context:nil]; CGSize size = rect.size; CGFloat height = MAX(size.height + 82, 100.0f); return height;
}
|
然后运行,就可以啦
百度药丸~