我在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