我在Xcode接口构建器中制作了一个自定义TableViewCell,其中UILabel和UITextView垂直堆叠,并设置了它们与容器单元格视图之间的垂直间距约束。



UITextView可能需要容纳很多文本,我不希望出现垂直滚动条,所以我用[NSString sizeWithFont:constraintTosize:]计算UITextView的高度,并用这个新高度设置它的框架。

但这是行不通的。

然后我注意到.xib中的自定义单元格具有固定的行高。我想知道这个固定的高度和垂直约束是否确定UITextView的高度,我不能更改它吗?

如果我想反过来怎么办:当我设置UITextView的高度时,将根据约束条件来计算包含单元格的高度?这可能吗?

最佳答案

以下代码应该会有所帮助。我能够执行您要描述的内容,并在UILabel的自定义UITableViewCell内将CustomCell上的文本量考虑在内。 CustomCell使用样板代码UITableViewCell未经修改。

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    // Configure the cell...
    // Using some sample text in here for testing purposes.
    NSString *sampleText = @"The UITextView may need to hold a lot of text, I don't want vertical scrollbar to appear. The UITextView may need to hold a lot of text, I don't want vertical scrollbar to appear.";

    cell.textLabel.text = sampleText;
    [cell.textLabel layoutIfNeeded];

    return cell.textLabel.frame.size.height;
}


最后但并非最不重要的一点是,使用AutoLayout在UILabel中设置您的CustomCell。单击此链接以查看有关此操作的步骤:https://stackoverflow.com/a/16009707/885189

10-07 12:38
查看更多