How do I create a multiline table cell in iOS?

前端 未结 4 1530
暖寄归人
暖寄归人 2021-02-03 13:40

How can I get the second cell to expand to fit the text rather than scaling the text? Is there a built in way of doing this in iOS or will I have to come up with some home-cook

4条回答
  •  野性不改
    2021-02-03 14:12

    I just ran into this same problem. I found an alternative solution that doesn't require quite as much hardcoding, and allows you to make modifications to the label in Interface Builder that will be reflected in the height calculation.

    - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
    {
         if (indexPath.section == 0 && indexPath.row == 1) {
            NSString *text = [atmAnnotation address];
            UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:@"MyIdentifier"];
    
            cell.textLabel.text = text;
            [cell.textLabel sizeToFit];
    
            CGFloat height = MAX( 44, cell.textLabel.bounds.size.height );
    
            return height + CELL_CONTENT_MARGIN * 2;
        }
    
        return 44.0f;
    }
    

    The only downside is that this will cause some additional temporary UITableViewCell allocations, but the table view will immediately reclaim them, so I don't think it should be a big problem.

提交回复
热议问题