iphone - 使用 NSString sizeWithFont :constrainedToSize:lineBreakMode: 调整大小时,表格单元格最后一行被截断

标签 iphone objective-c ios cocoa-touch

当使用以下代码调整表格行的大小时,无论有多少行,最后一行文本总是被截断。但是添加了空白,看起来足以容纳文本。

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
    CGFloat restOfTheCellHeight = tableView.rowHeight - cell.detailTextLabel.frame.size.height;
    CGSize constrainedSize = CGSizeMake(cell.detailTextLabel.frame.size.width, CGFLOAT_MAX);
    CGSize textHeight = [cell.detailTextLabel.text sizeWithFont:cell.detailTextLabel.font constrainedToSize:constrainedSize lineBreakMode:cell.detailTextLabel.lineBreakMode];
    CGFloat newCellHeight = (textHeight.height + restOfTheCellHeight);
    if (tableView.rowHeight > newCellHeight) {
        newCellHeight = tableView.rowHeight;
    }
    return newCellHeight;
}

这是 cellForRowAtIndexPath 中的代码:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CustomCellTableRowTypeSingleLineValueSmallLabel *cell = (CustomCellTableRowTypeSingleLineValueSmallLabel *)[tableView dequeueReusableCellWithIdentifier:@"CellTypeMultiLineLabelInCellSmallCell"];

    if (cell == nil) {
        NSArray *xibObjects = [[NSBundle mainBundle] loadNibNamed:@"CustomCellTableRowTypeSingleLine" owner:nil options:nil];
        for(id currentObject in xibObjects) {
            if([currentObject isKindOfClass:[CustomCellTableRowTypeSingleLineValueSmallLabel class]]){
                cell = (CustomCellTableRowTypeSingleLineValueSmallLabel *)currentObject;
            }
        }
        cell.accessoryType = UITableViewCellAccessoryNone;
        cell.editingAccessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }   

    cell.detailTextLabel.lineBreakMode = UILineBreakModeWordWrap;
    cell.detailTextLabel.numberOfLines = 0;

    cell.detailTextLabel.text = self.attributeStringValue;
    cell.textLabel.text = self.rowLabel;

    return cell;
}

有什么想法吗?

最佳答案

您需要调用 [cell.detailTextLabel sizeToFit] 以便标签在 cellForRowAtIndexPath 中实际调整大小。它不会因为您将 numberOfLines 设置为 0 而自行调整大小。参见 this question and read its answers以获得更多说明。

关于iphone - 使用 NSString sizeWithFont :constrainedToSize:lineBreakMode: 调整大小时,表格单元格最后一行被截断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7111267/

相关文章:

ios - statusCode 应该是 200,但是是 415

ios - 从 imagePicker 选择图像时,iOS11.2.6、Xcode 9.2 应用程序崩溃

iphone - 从 iOS 照片库获取图片数据

ios - 是否可以在 JSON 数据中搜索特定键?

ios - 旋转后翻译 UIView

ios - 在具有较大 contentSize 的 UIScrollView 中居中 UIImageView

iphone - IOS6 中 UINavigationController 中的 UIView 方向

iphone - 是否有任何 Windows 模拟器可用于测试 iPhone 应用程序?

objective-c - 代码 : Count elements in string array

ios - 如何在uitextview或uiimage中点按突出显示特定句子