動態設置UITableViewCell的高度



目的:計算出圖中紅色部分的實際高度,根據字體大小、字型、內容長短自動算出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;
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章