我在 Xcode 界面生成器中制作了一个自定义 TableViewCell,其中 UILabel 和 UITextView 垂直堆叠,并设置了它们与容器单元 View 之间的垂直间距的约束。
UITextView 可能需要容纳大量文本,我不希望出现垂直滚动条,因此我使用 [NSString sizeWithFont:constraintTosize:] 计算 UITextView 的高度,并用这个新高度设置其框架。
但是这不起作用。
然后我注意到 .xib 中的自定义单元格具有固定的行高。我想知道这个固定高度和垂直约束是否决定了 UITextView 的高度,并且我无法更改它?
如果我想要相反怎么办:当我设置 UITextView 的高度时,包含单元格的高度是根据约束计算的?这可能吗?
最佳答案
下面的代码应该会有帮助。我能够按照您的描述进行操作,并在名为 CustomCell
的自定义 UITableViewCell
中处理 UILabel
上的可变文本量。 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 在 CustomCell
中设置您的 UILabel
。点击此链接查看操作步骤:https://stackoverflow.com/a/16009707/885189
关于ios - 如何根据自动布局约束使容器 View 的高度动态化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19853376/