iOS计算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;
}

顺便说一句,还有其他奇怪的事情。如果我滚动表视图,整个应用程序似乎会冻结。这是正常的还是我做错了什么?

为您的问题尝试这个:

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

希望能有所帮助。

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

iOS 7 sizeWithAttributes:sizeWithFont:contrainedToSize

的替换

最新更新