如何根据文字的多少动态的调整TableViewCell的高度

匿名 (未验证) 提交于 2019-12-03 00:14:01

开发中经常会遇到需要动态调整UITableViewCell的高度的问题,这个问题百度到的十分不清楚,但是谷歌到的就十分清楚,在百度没完之前我还是自己还是记录下吧……

在storyboard中设置label的约束如图所示:

或者:

然后在viewDidLoad中添加

12
self.tableView.rowHeight = UITableViewAutomaticDimension;self.tableView.estimatedRowHeight = 44;

tableView需要设置为Dynamic Prototypes,上图的约束一条都不能少!!

12345678910111213141516171819202122232425262728293031
#define ScreenSize ScreenFrame.size#define FONT_SIZE 15.0f#define CELL_CONTENT_WIDTH ScreenSize.width //CELL_CONTENT_WIDTH 为cell的宽度#define CELL_CONTENT_MARGIN 8.0f //CELL_CONTENT_MARGIN为label距cell两边的宽度- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{    NSDictionary *rowData = _dataArray[indexPath.section];    text = [rowData objectForKey:@"content"];    //CELL_CONTENT_WIDTH 为cell的宽度;CELL_CONTENT_MARGIN为label距cell两边的宽度,相减得到label长度~;后面的20000任意设置    CGSize constraint = CGSizeMake(CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 2), 20000.0f);        //CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];        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;    }

然后运行,就可以啦

百度药丸~

原文:大专栏如何根据文字的多少动态的调整TableViewCell的高度


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!