iOS在tableView单元格中计算文本高度 [英] iOS calculate text height in tableView cell
本文介绍了iOS在tableView单元格中计算文本高度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我目前正在开发一款应用,它会在tableview中显示一些推文。在故事板上我创建了一个原型单元格,其中包含了一条推文条目的基本gui概念。
i'm currently developing on an app, which displays some tweets in a tableview. On the storyboard i created a prototype-cell, which includes the basic gui concept of a tweet entry.
看起来大概是这样的:
++++++++++++++
++Username++++
++++++++++++++
++Tweet+++++++
++++++++++++++
++Time-Ago++++
++++++++++++++
现在我用以下代码计算单元格的高度但不知怎的,它失败了。
Now i'm calculating the height of the cell with the following code, but somehow it fails.
- (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,整个应用程序似乎冻结。这是正常的还是我做错了什么?
By the way, there is something other, which is strange. If i scroll the tableview the whole app seems to freeze. Is this normal or am i doing something wrong?
推荐答案
试试这个问题:
- (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在tableView单元格中计算文本高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文