我正在尝试使 UITableView
与 UITextView
中段落的高度大小对齐。 示例:左侧的时间戳是我想要做的。我更改了代码以使用 UIView 而不是 TVcell 来查看问题所在,您可以看到橙色 View 与青色 View 重叠,这意味着 View 实际上并未对齐,但它们重叠。 注意:我想使用 TableView 而不是 UIView 的 我无法理解 iOS 中文本高度的计算方式。我使用下面的代码来获取每个段落
的高度:
let liveParagraphView = textView.selectionRects(for: txtRange).reduce(CGRect.null) { $0.union($1.rect) }
之后,我计算每个的高度,然后将其输入到我的 UITableView heightForRowAt
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
let models = getParagraphModel()
let height = models[indexPath.row].height
let finalHeight = models[indexPath.row].height
let heightValue = finalHeight
return CGFloat(heightValue);
}
每条线都有不同的高度值,但即使使用这些值,它也不会对齐。问题似乎是每行计算的 Y 位置并不直接位于其之前的行下方。它在顶部!!导致添加新单元格时 UITableView 不对齐,并且不考虑选择矩形的“覆盖”。我的说法正确吗?我怎样才能实现这一目标?
最佳答案
swift 5
首先,您应该设置 textView(位于单元格中)动态高度:
textView.translatesAutoresizingMaskIntoConstraints = true
textView.sizeToFit()
textView.isScrollEnabled = false
然后在textDidChange
等中计算textView的行数,以更新tableView的布局。
让 numOfLines = (yourTextView.contentSize.height/yourTextView.font.lineHeight) 作为?整数
当 textView 的文本向下一行时,您应该更新 tableView 布局:
tableView.beginUpdates()
tableView.endUpdates()
然后您应该将 tableView 单元格的内在内容大小设置为动态 rowHeight:
设置单元格(包含 textView)的布局,不设置静态高度,
设置 tableView 的
rowHeight
和estimatedRowHeight
:tableView.rowHeight = UITableView.automaticDimension tableView.estimatedRowHeight = 44 // whatever you want
现在你有了具有动态高度的 tableView 单元
关于ios - UITableView 与 UITextView 对齐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56766085/