【发布时间】:2021-08-28 07:14:21
【问题描述】:
我创建了一个自定义视图MyIntrincView,它会在设置其内容时自动计算其高度。这在模拟器和 InterfaceBuilder 中都可以正常工作。
但是,当将MyIntrinsicView 放在UITableViewCell 中时,单元格高度未正确计算。所有单元格都保持相同的初始高度,而不是自动将单元格高度设为视图的固有高度。
// A simple, custom view with intrinsic height. The height depends on
// the value of someProperty. When the property is changed setNeedsLayout
// is set and the height changes automatically.
@IBDesignable class MyIntrinsicView: UIView {
@IBInspectable public var someProperty: Int = 5 {
didSet { setNeedsLayout() }
}
override func layoutSubviews() {
super.layoutSubviews()
calcContent()
}
func calcContent() {
height = CGFloat(20 * someProperty)
invalidateIntrinsicContentSize()
}
@IBInspectable var height: CGFloat = 50
override var intrinsicContentSize: CGSize {
return CGSize(width: super.intrinsicContentSize.width, height: height)
}
override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
invalidateIntrinsicContentSize()
}
}
// A simple cell which only contains a MyIntrinsicView subview. The view
// is attached to trailing, leading, top and bottom anchors of the cell.
// Thus the cell height should automatically match the height of the
// MyIntrinsicView
class MyIntrinsicCell: UITableViewCell {
@IBOutlet private var myIntrinsicView: MyIntrinsicView!
var someProperty: Int {
get { return myIntrinsicView.someProperty }
set {
myIntrinsicView.someProperty = newValue
// Cell DOES NOT rezise without manualle calling layoutSubviews()
myIntrinsicView.layoutSubviews()
}
}
}
...
// Simple tableView delegate which should create cells of different heights
// by giving each cell a different someProperty
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "IntrinsicCell", for: indexPath) as? MyIntrinsicCell ?? MyIntrinsicCell()
// Give all cell a different intrinsic height by setting someProperty to rowIndex
cell.someProperty = indexPath.row
return cell
}
我希望每个单元格都有不同的高度 (20 * someProperty = 20 * indexPath.row)。但是,所有单元格都具有相同的初始高度。
仅当显式调用 myIntrinsicView.layoutSubviews() 时,才会创建具有正确高度的单元格。
tableView 好像没有调用myIntrinsicView.layoutSubviews()。 这是为什么?
当使用 UILabel 或 MyIntrinsicView 作为具有不同文本长度的单元格内容时,一切都按预期工作。因此,整个 tableView 设置是正确的(= 单元格大小是自动计算的),并且必须有办法在 UITableView 中正确使用内在大小。 那么,正确的做法是什么?
【问题讨论】:
标签: ios uitableview intrinsic-content-size