iOS计算tableView单元格中的文本高度

标签 ios ipad uitableview storyboard cell

我目前正在开发一个应用程序,它在表格 View 中显示一些推文。在 Storyboard上,我创建了一个原型(prototype)单元格,其中包括推文条目的基本图形用户界面概念。

看起来大概是这样的:

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

对了,还有一点很奇怪。如果我滚动表格 View ,整个应用程序似乎会卡住。这是正常现象还是我做错了什么?

最佳答案

试试这个解决你的问题:

- (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单元格中的文本高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14841193/

相关文章:

ios - 无法在 Swift 中将类型 'UITableViewCell' 的值转换为 'NSIndexPath'

ios - parse.com 存储特定值一次

iphone - 从 double 中删除最后 6 位数字(Objective-C)

ios - 核心数据,enitityForName nil 错误

ios - 如何在 Xcode 9 和 iOS 11 中进行无线调试?没有密码

ios - 除非选择单元格,否则 UITableViewCell 中的按钮不会显示

ios - 从转换后的 json 字符串中删除\n 和斜杠\

iphone - 应用程序适用于模拟器但不适用于设备

iphone - 我正在努力比较我制作的 UIcolor

ios - 根据 uitableview 单元格值调用函数