UITableViewCell自适应高度
方式一:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { //cell宽度取系统cell width; CGFloat contentwidth = self.tableView.frame.size.width; //字体大小和下面的 heightForCell保持一致; UIFont *font = [UIFont systemFontOfSize:17.0]; //当前cell数据; NSString *contentText = [self.dataArray objectAtIndex:indexPath.row]; //计算cell数据文本大小; CGSize contentSize = [contentText sizeWithFont:font constrainedToSize:CGSizeMake(contentwidth, 1000) lineBreakMode:NSLineBreakByCharWrapping]; static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (!cell) { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; } //重置cell rect大小; CGRect cellRect = [cell.textLabel textRectForBounds:cell.textLabel.frame limitedToNumberOfLines:0]; cellRect.size = contentSize; cell.textLabel.frame = cellRect; cell.textLabel.text = contentText; //设置cell的textLable可以多行文本显示; cell.textLabel.numberOfLines = 0; //设置字体大小和颜色; cell.textLabel.textColor = [UIColor blueColor]; cell.textLabel.font = font; return cell; } - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { //重新计算每行的cell的高度; CGFloat contentWith = self.tableView.frame.size.width; UIFont *font = [UIFont systemFontOfSize:17.0]; NSString *content = [self.dataArray objectAtIndex:indexPath.row]; CGSize contentSize = [content sizeWithFont:font constrainedToSize:CGSizeMake(contentWith, 1000) lineBreakMode:NSLineBreakByCharWrapping]; return contentSize.height+25; }
方式二:
UITableViewCell 里面的 layoutSubViews方法里面写

//再画布重绘的时候,重置cell自适应高度; -(void)layoutSubviews { [super layoutSubviews]; _cou_title.text = _dataModel.cou_title; _cou_publish_date.text = [NSString stringWithFormat:@"发布日期:%@",_dataModel.cou_publish_date]; _cou_expiration_date.text = [NSString stringWithFormat:@"结束日期:%@",_dataModel.cou_expiration_date]; _cou_description.text = _dataModel.cou_description; CGSize descriSize = [_dataModel.cou_description sizeWithFont:[UIFont systemFontOfSize:15.0] constrainedToSize:CGSizeMake(300, 200) lineBreakMode:NSLineBreakByCharWrapping]; _cou_description.frame = CGRectMake(_cou_description.frame.origin.x, _cou_description.frame.origin.y,_cou_description.frame.size.width, descriSize.height); }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具