1

我正在尝试为表格中的单元格设置动态高度,高度应基于文本长度和最大宽度。

当此文本出现在一行中,没有行分隔符时,就会出现问题。不管文本有多大,如果没有行分隔符,它会检测到文本适合单行,因此我的单元格高度不会增加。

难道我做错了什么?我怎样才能实现它?谢谢。

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

    CGFloat cellheight = 35.0f; // BASE

    NSString *text = @"...";

    if (text) {
    UIFont *font = (indexPath.row == 0) ? [UIFont systemFontOfSize:14] : [UIFont systemFontOfSize:12]; 
    CGSize constraintSize = CGSizeMake(self.tableView.frame.size.width, CGFLOAT_MAX);

    if (IS_EARLIER_THAN_IOS7) {
        CGSize size = [text sizeWithFont:font constrainedToSize:constraintSize lineBreakMode:NSLineBreakByCharWrapping];
        cellheight += size.height;
    } else {
        CGSize size = [text sizeWithAttributes:@{NSFontAttributeName: [UIFont systemFontOfSize:12.0f]}];

        CGSize adjustedSize = CGSizeMake(ceilf(size.width), ceilf(size.height));
        cellheight += adjustedSize.height;
    }
    return (indexPath.row == 0) ? cellheight + 40.0f : cellheight;
}  

}

4

2 回答 2

2
- (CGSize)sizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size lineBreakMode:(NSLineBreakMode)lineBreakMode NS_DEPRECATED_IOS(2_0, 7_0, "Use -boundingRectWithSize:options:attributes:context:") __TVOS_PROHIBITED; // NSTextAlignment is not needed to determine size

您应该使用“boundingRectWithSize:options:attributes:context:”而不是“sizeWithAttributes:”。

这是一个样本

CGSize size = [text boundingRectWithSize:CGSizeMake(_myTableView.frame.size.width, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14]} context:nil].size;
于 2016-01-14T09:32:08.423 回答
2

有一种更简单的方法可以做到这一点:

首先将文本设置为UILabel,并设置所有需要的字体、大小。等然后调用sizeThatFits标签上的方法。

CGSize sizze =[itemLabel sizeThatFits:CGSizeMake(itemNameLabelWidth, CGFLOAT_MAX)];

也不要忘记在调用之前设置numberOfLineslineBreakModesizeThatFits:

itemLabel.numberOfLines=0;
itemLabel.lineBreakMode=NSLineBreakByWordWrapping;

注 1:调用sizeThatFits不会将新帧设置为 UILabel,它只是计算并返回新帧。然后,您必须通过添加 x 和 y 原点值将框架设置为标签。这样就变成了:

CGSize sizze =[itemLabel sizeThatFits:CGSizeMake(itemNameLabelWidth, CGFLOAT_MAX)];
CGRect namelabelFrame = itemLabel.frame;
namelabelFrame.size = sizze;
itemLabel.frame = namelabelFrame;

注意 2:这段代码在 中是可以的cellForRowAtIndexPath:,但是在计算里面的高度时,heightForRowAtIndexPath:你可能需要稍微优化一下这段代码。由于您没有可以使用的单元格,您可能会初始化一个UILabel对象并在其上执行此代码以估计高度。但是在UIView内部进行初始化heightForRowAtIndexPath:并不是一个好主意,因为它们会在滚动时显着影响性能。

因此,您所做的是将已经初始化(并应用​​了所有格式)UILabel作为类变量,并将其重用于高度计算。

于 2016-01-14T08:57:42.440 回答