Swift:table 视图中的动态单元格
Swift: Dynamic Cell in table view
我试图使 table 视图单元格的高度 = 单元格的内容。
我在 viewDidLoad()
中实现了这两行:
tableView.estimatedRowHeight = 200.0
tableView.rowHeight = UITableViewAutomaticDimension
仍然,单元格正在改变它的高度!
尝试使用 heightForRowAt indexpath
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {return UITableViewAutomaticDimension}
+
override func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
在我看来,您的问题可能是未明确说明 UITextView
的高度。文本视图的自然行为与其内容一样高。
我建议在 Interface Builder 中添加高度约束,将其连接到插座,然后在单元格 layoutSubviews
函数中计算高度,如下所示:
@IBOutlet var textViewHeightConstraint: NSLayoutConstraint!
func layoutSubviews() {
super.layoutSubviews()
let fixedWidth = textView.frame.size.width
textView.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.greatestFiniteMagnitude))
let newSize = textView.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.greatestFiniteMagnitude))
textViewHeightConstraint.constant = newSize.height
}
默认情况下,TextView 不会展开以适应整个文本,因为它具有滚动功能,对于您想要的内容,您应该禁用 textView 中的滚动。
Select textView 并在“属性检查器”选项卡中向下滚动并取消选中 "Scrolling Enabled"
在 ViewDidLoad 中
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 200
并将标题标签和文本标签(替换文本视图)都放在 UIView 中。并对 UIView 进行约束
1. 尾随、前导、底部和顶部 space 为零
2. 将固定高度设置为 200 并将关系更改为大于或等于 (>=)
然后对Title标签进行约束
1. 尾随、前导和顶部 space 为零
2. 将固定高度设置为 20(您的选择)
对文本标签进行约束
1. 尾随、前导、底部和顶部 space 为零
2. 将固定高度设置为 180 并将关系更改为大于或等于 (>=)
我试图使 table 视图单元格的高度 = 单元格的内容。
我在 viewDidLoad()
中实现了这两行:
tableView.estimatedRowHeight = 200.0
tableView.rowHeight = UITableViewAutomaticDimension
仍然,单元格正在改变它的高度!
尝试使用 heightForRowAt indexpath
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {return UITableViewAutomaticDimension}
+
override func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
在我看来,您的问题可能是未明确说明 UITextView
的高度。文本视图的自然行为与其内容一样高。
我建议在 Interface Builder 中添加高度约束,将其连接到插座,然后在单元格 layoutSubviews
函数中计算高度,如下所示:
@IBOutlet var textViewHeightConstraint: NSLayoutConstraint!
func layoutSubviews() {
super.layoutSubviews()
let fixedWidth = textView.frame.size.width
textView.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.greatestFiniteMagnitude))
let newSize = textView.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.greatestFiniteMagnitude))
textViewHeightConstraint.constant = newSize.height
}
默认情况下,TextView 不会展开以适应整个文本,因为它具有滚动功能,对于您想要的内容,您应该禁用 textView 中的滚动。
Select textView 并在“属性检查器”选项卡中向下滚动并取消选中 "Scrolling Enabled"
在 ViewDidLoad 中
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 200
并将标题标签和文本标签(替换文本视图)都放在 UIView 中。并对 UIView 进行约束
1. 尾随、前导、底部和顶部 space 为零
2. 将固定高度设置为 200 并将关系更改为大于或等于 (>=)
然后对Title标签进行约束
1. 尾随、前导和顶部 space 为零
2. 将固定高度设置为 20(您的选择)
对文本标签进行约束
1. 尾随、前导、底部和顶部 space 为零
2. 将固定高度设置为 180 并将关系更改为大于或等于 (>=)