将UITableViewCell的大小动态调整为UILabel的高度

Rah*_*yas 15 math objective-c uitableview ios

我想根据标签的高度和标签的高度调整单元格的高度.或者有什么方法可以根据输入的文本调整单元格的高度UITextView

小智 17

自iOS 7.0以来,这种方法已被弃用.

在创建单元格或表之前,会调用一个UITableView名为的委托方法heightForRowAtIndexPath.

您可以使用NSIndexPath传递给它来获取特定行的文本,并使用sizeWithFont方法UIStringDrawing.h来计算CGSize该行的行.

例如:

CGSize size = [text sizeWithFont:font
                   constrainedToSize:maximumLabelSize
                   lineBreakMode:UILineBreakModeWordWrap];
Run Code Online (Sandbox Code Playgroud)

最后你会回来size.height.

  • 此方法已在iOS7中弃用. (3认同)

dig*_*und 6

- 适用于iOS7--

基于Josh Vera的答案......将它放在heightForRowAtIndexPath中.

我将表数据存储在NSArray*tableData中.

// set the desired width of the textbox that will be holding the adjusted text, (for clarity only, set as property or ivar)
CGFloat widthOfMyTexbox = 250.0;

-(float)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //Get a reference to your string to base the cell size on.
    NSString *cellText = [self.tableData objectAtIndex:indexPath.row];
    //set the desired size of your textbox
    CGSize constraint = CGSizeMake(widthOfMyTextBox, MAXFLOAT);
    //set your text attribute dictionary
    NSDictionary *attributes = [NSDictionary dictionaryWithObject:[UIFont systemFontOfSize:14.0] forKey:NSFontAttributeName];
    //get the size of the text box
    CGRect textsize = [cellText boundingRectWithSize:constraint options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil];
    //calculate your size
    float textHeight = textsize.size.height +20;
    //I have mine set for a minimum size
    textHeight = (textHeight < 50.0) ? 50.0 : textHeight;

    return textHeight;
}
Run Code Online (Sandbox Code Playgroud)

我没有为iOS <7测试它,但我相信它也适用于此.