问题描述
在故事板上,我有一个UITableView
和动态生成的UITableViewCell
.每个单元格包含2个标签和1个文本视图:
In my story board I have a UITableView
with dynamically generated UITableViewCell
s. Each cell contains 2 labels and 1 text view:
我有一个代码可以将文本字段的大小调整为文本量:
I have a code that adjust the size of the textfield to the amount of text:
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的背景色设置为红色时,我会看到:
and it works fine, when I set a background color of my textView to red I see:
和单元格本身-我在此处设置大小:
and the cell itself - I'm setting the size in here:
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?
}
}
正如我在上面的评论中所写-如何根据文本视图中的文本量动态设置单元格的高度?
So as I wrote in the comment above - how can I set the height of the cell dynamically based on the amount of text in the text view?
推荐答案
获取自定义表格单元格(基于自动布局,我建议)的关键如下:
The key to getting self-sizing table cells (autolayout-based, which I recommend) is as follows:
- 将子视图添加到
UITableViewCell
的 - 在子视图和
contentView
之间提供约束,以使子视图到达表单元格的所有边缘.在您的情况下,这可能意味着将UITextView
的leading
,trailing
,top
和bottom
边缘与contentView
的相应边缘对齐. - 将行高设置为
UITableViewAutomaticDimension
,而不是硬编码的CGFloat
. - 在控制器中的某个位置,用
tableView.estimatedRowHeight = x
提供高度估计(硬编码常数很好,这是为了提高性能).
contentView
- Add your subviews to the
contentView
of theUITableViewCell
- Provide constraints between your subviews and the
contentView
such that your subviews reach all edges of the table cell. In your case, this probably means aligning theleading
,trailing
,top
, andbottom
edges of yourUITextView
to the corresponding edges of thecontentView
. - Set the row height to
UITableViewAutomaticDimension
instead of a hardcodedCGFloat
. - Somewhere in your controller, provide an estimation of the height with
tableView.estimatedRowHeight = x
(a hard coded constant is fine, this is for performance).
这篇关于如何将UITableViewCell的高度调整为内部UITextView的内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!