How to resize UITableViewCell to fit its content?

前端 未结 8 752
有刺的猬
有刺的猬 2020-12-08 05:34

I have a UITableview with multiple reusable TableViewCells. In one cell I have a UITextView, that resizes itself to fit its content. Now I \"just\

8条回答
  •  Happy的楠姐
    2020-12-08 05:37

    You need you implement heightForRowAtIndexPath.

    Say that the data that is to be displayed in the textView is stored in a NSArray.

    - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
     CGFloat cellheight = 30; //assuming that your TextView's origin.y is 30 and TextView is the last UI element in your cell
    
     NSString *text = (NSString *)[textArray objectAtIndex:indexpath.row];
     UIFont *font = [UIFont systemFontOfSize:14];// The font should be the same as that of your textView
     CGSize constraintSize = CGSizeMake(maxWidth, CGFLOAT_MAX);// maxWidth = max width for the textView
    
     CGSize size = [text sizeWithFont:font constrainedToSize:constraintSize lineBreakMode:UILineBreakModeWordWrap];
    
     cellHeight += size.height; //you can also add a cell padding if you want some space below textView
    
    }
    

提交回复
热议问题