【问题标题】:Resize UITableViewCell to UILabel's height dynamically动态调整 UITableViewCell 到 UILabel 的高度
【发布时间】:2010-11-03 23:37:29
【问题描述】:

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

【问题讨论】:

  • 您是说要在文本视图中输入更多文本时调整包含 UITextView 的 UITableViewCell 的大小?
  • 不,先生,我有一个自定义单元格,单元格上有标签。文本来自数据库。如何增加单元格行高和标签行数或标签高度,以便长文本可以适合单元格的标签

标签: ios objective-c uitableview math


【解决方案1】:

此方法自 iOS 7.0 起已弃用。

有一个名为heightForRowAtIndexPathUITableView 委托方法会在您创建单元格或表格之前调用。

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

例如:

CGSize size = [text sizeWithFont:font
                   constrainedToSize:maximumLabelSize
                   lineBreakMode:UILineBreakModeWordWrap];

最后你会返回size.height

【讨论】:

  • 此方法在 iOS7 中已被弃用。
【解决方案2】:

--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;
}

我还没有在 iOS

【讨论】:

  • 你能解释一下 widthOfMyTextBox 指的是什么吗?
  • Scratcha 查看更新的答案。这是您希望文本框的宽度。
猜你喜欢
  • 2015-03-25
  • 2016-08-19
  • 1970-01-01
  • 2011-03-05
  • 2012-10-18
  • 1970-01-01
  • 2016-06-23
  • 1970-01-01
  • 2021-10-27
相关资源
最近更新 更多