问题 iOS在tableView单元格中计算文本高度


我目前正在开发一个应用程序,它在tableview中显示一些推文。在故事板上我创建了一个原型单元格,其中包括推文条目的基本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,整个应用程序似乎冻结。这是正常的还是我做错了什么?


11946
2018-02-12 20:27


起源

@ freeze是不正常的。从外面来看,我有一种感觉,这可能是由于以下两个原因之一:1)你做了太多的计算,因为它导致了这一点。 2)为了以格式化的方式显示文本,显然您可能在每个行的文本上使用某种编码。 - Reno Jones
您好,感谢您的评论。你是对的。我每秒都调用[tableView reloadData]来更新秒前计数器。我取下了柜台,冻结了。我想在cellview中做这个。 :) - Lucè Brùlè
这很酷。 :) - Reno Jones
在tableView.visibleCells上做一个foreach,并用当前时间更新每个。正如您所发现的那样,不惜一切代价避免重新加载数据。 :) - escrafford
您用于计算可变高度文本单元格的方法与我之前成功完成的方法相同 - 这与我之前设法完成的方法一样快。 - escrafford


答案:


试试这个问题:

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

希望能帮助到你。


13
2018-02-12 20:39



sizeWithFont 和 UILineBreakModeWordWrap 已弃用 - aykutt


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

iOS 7 sizeWithAttributes:替换sizeWithFont:constrainedToSize


3
2018-02-16 00:43