目的:计算出图中红色部分的实际高度,根据字体大小、字型、内容长短自动算出UILabel的高度。
代码如下:
- (CGFloat)tableView:(__unused UITableView *)tableView heightForRowAtIndexPath:(__unused NSIndexPath *)indexPath
{
//除了content之外的其他高度总和,这个你可以从布局文件中得到(上图中的红色部分除外的其他部分高的总和)
float cellHeight = 55.0f;
//获取Cell
AlarmAlertCell *cell = (AlarmAlertCell *)[self tableView:tableView cellForRowAtIndexPath:indexPath];
//获取数据源
AlarmNSString *data = [_dataSource objectAtIndex:indexPath.row];
//获取高度
CGSize size = [data.content sizeWithFont:cell.message.font constrainedToSize:CGSizeMake(cell.message.frame.size.width, MAXFLOAT) lineBreakMode:NSLineBreakByWordWrapping];
//得到当前字体所显示的行数
int cellRow = size.height/14;
//通过行数算出content所占的实际高度
cellHeight = cellHeight + (14+7)*cellRow;
NSLog(@"cellHeight = %f", cellHeight);
return cellHeight;
}
本文提供了一个Swift代码示例,用于根据字体大小、字型和内容长度自动计算UILabel的高度,包括获取数据源、计算字体显示的行数以及最终得出实际高度。
1万+

被折叠的 条评论
为什么被折叠?



