我怎样才能调整UITableViewCell高度的内部UITextView的内容?
在我的故事板中,我有一个带有dynamic生成的UITableViewCell
。 每个单元格包含2个标签和1个文本视图:
我有一个代码,将文本字段的大小调整为文本的大小:
let fixedWidth = cell.myComment.frame.size.width cell.myComment.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.max)) let newSize = cell.myComment.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.max)) var newFrame = cell.myComment.frame newFrame.size = CGSize(width: max(newSize.width, fixedWidth), height: newSize.height) cell.myComment.frame = newFrame;
它工作正常,当我设置我的textView的背景色为红色,我看到:
和细胞本身 – 我在这里设置大小:
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { if indexPath.row == 0 { return 100//this is my static cell } else { return 117; //for now it's hardcoded - how can I set this value dynamically based on content? } }
所以当我在上面的评论中写道 – 如何根据文本视图中文本的数量dynamic设置单元格的高度?
获取自定表格单元格的关键(自动布局,我推荐)如下:
- 将你的子视图添加到
UITableViewCell
的contentView
- 在子视图和
contentView
之间提供约束,使得子视图到达表格单元格的所有边缘。 在你的情况下,这可能意味着将UITextView
的leading
,trailing
,top
和bottom
边缘alignment到contentView
的相应边缘。 - 将行高设置为
UITableViewAutomaticDimension
而不是硬编码的CGFloat
。 - 在你的控制器的某个地方,用
tableView.estimatedRowHeight = x
提供一个高度估计(硬编码常数是好的,这是为了性能)。