【问题标题】:iOS calculate text height in tableView celliOS计算tableView单元格中的文本高度
【发布时间】:2013-01-28 06:28:12
【问题描述】:

我目前正在开发一个应用程序,该应用程序在表格视图中显示一些推文。在故事板上,我创建了一个原型单元,其中包含推文条目的基本 gui 概念。

大概是这样的:

++++++++++++++
++Username++++
++++++++++++++
++Tweet+++++++
++++++++++++++
++Time-Ago++++
++++++++++++++

现在我正在使用以下代码计算单元格的高度,但不知何故它失败了。

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSDictionary * currentTweet = [tweetArray objectAtIndex: indexPath.row];
    NSString * tweetTextString = [currentTweet objectForKey: @"text"];
    CGSize textSize = [tweetTextString sizeWithFont:[UIFont systemFontOfSize:15.0f] constrainedToSize:CGSizeMake(630, 1000) lineBreakMode: NSLineBreakByWordWrapping];

    float heightToAdd = 24 + textSize.height + 15 + 45;
    if(heightToAdd < 90) {
        heightToAdd = 90;
    }

    return heightToAdd;
}

顺便说一句,还有别的东西,很奇怪。如果我滚动 tableview 整个应用程序似乎冻结。这是正常的还是我做错了什么?

【问题讨论】:

  • 不正常@冻结。从外部,我有一种感觉,这可能是由于以下两个原因之一:1)您进行了太多计算,因此导致了这种情况。 2)为了以格式化的方式显示文本,显然您可能正在对每一行的文本使用某种编码。
  • 您好,感谢您的评论。你说得对。我每秒调用 [tableView reloadData] 来更新秒前计数器。我移开柜台,冻结停止了。我正在尝试在 cellview 中执行此操作。 :)
  • 在 tableView.visibleCells 上做一个 foreach 并用当前时间更新它们。如您所见,不惜一切代价避免 reloadData 。 :)
  • 您用于计算可变高度文本单元格的方法与我之前成功完成的方法相同 - 这与我之前设法做到的速度一样快。
  • 您好,谢谢您的帮助。我玩了一点,终于让它工作了!谢谢:)

标签: ios ipad uitableview storyboard cell


【解决方案1】:

试试这个解决你的问题:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

    NSDictionary * currentTweet = [tweetArray objectAtIndex: indexPath.row];

    NSString * tweetTextString = [currentTweet objectForKey: @"text"];

    CGSize textSize = [tweetTextString sizeWithFont:[UIFont systemFontOfSize:15.0f] constrainedToSize:CGSizeMake(240, 20000) lineBreakMode: UILineBreakModeWordWrap]; //Assuming your width is 240

    float heightToAdd = MIN(textSize.height, 100.0f); //Some fix height is returned if height is small or change it to MAX(textSize.height, 150.0f); // whatever best fits for you

    return heightToAdd;
}

希望对你有帮助。

【讨论】:

  • sizeWithFont 和 UILineBreakModeWordWrap 已弃用
【解决方案2】:

如果您正在寻找我在这里遇到的 iOS 7 答案:

iOS 7 sizeWithAttributes: replacement for sizeWithFont:constrainedToSize

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-14
    相关资源
    最近更新 更多