11

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

4

2 回答 2

13

试试这个解决你的问题:

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

希望能帮助到你。

于 2013-02-12T20:39:14.090 回答
3

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

iOS 7 sizeWithAttributes:替换 sizeWithFont:constrainedToSize

于 2014-02-16T00:43:45.277 回答