2013-02-12 35 views
10

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

它看起来大约是这样的:

++++++++++++++ 
++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整个应用程序似乎冻结。这是正常的还是我做错了什么?

+0

这是不正常@冻结。从外面看,我有一种感觉,这可能是由于两个原因之一造成的:1)你正在做太多的计算,因此导致了这一点。 2)为了以格式化的方式显示文本,显然你可能会在每一行的文本上使用某种编码。 – 2013-02-12 20:30:11

+0

您好,感谢您的评论。你是对的。我每秒调用一次[tableView reloadData]来更新秒前计数器。我取下了柜台,冻结停了下来。我正在尝试在cellview中执行此操作。 :) – 2013-02-12 20:37:11

+0

这很酷。 :) – 2013-02-12 20:40:13

回答

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

希望它能帮助。

+0

'sizeWithFont'和'UILineBreakModeWordWrap'已弃用 – aykutt 2016-09-25 10:30:48