我有一个带有嵌入式 UITableView 的 ContainerView。随着表中行数的增加,我希望 ContainerView 高度增加。我尝试过使用preferredContentSizeDidChange,但这没有效果。我不确定这个通知实际上是如何工作的。 TableView 是如何做到这一点的?有没有办法做到这一点?
class HomeVC: ContentViewController {
@IBOutlet weak var containerHeight: NSLayoutConstraint!
override func viewDidLoad() {
super.viewDidLoad()
}
override func preferredContentSizeDidChange(forChildContentContainer container: UIContentContainer) {
self.containerHeight.constant = container.preferredContentSize.height
UIView.animate(withDuration: 3, animations: {self.view.layoutIfNeeded()})
}
}
最佳答案
我将此函数添加到嵌入式 TableViewController 类中,每次更新表数据时都会调用该函数。它依赖于此处以及 heightForRowAt 中声明的 rowHeight,这似乎不正确,但它有效!
func adjustRowHeight() {
let rowHeight = CGFloat(100)
print("rowHeight is \(rowHeight)")
let newRowHeight = CGFloat(bLEManager.discoveredPeripherals.count) * rowHeight
print("newRowHeight is \(newRowHeight)")
self.preferredContentSize = CGSize(width: self.tableView.bounds.size.width, height: newRowHeight)
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 100
}
关于ios - 如何让带有嵌入式 UITableView 的 ContainerView 随着 tableView 单元格数量的变化而更新高度约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46949813/