ios - 如何让带有嵌入式 UITableView 的 ContainerView 随着 tableView 单元格数量的变化而更新高度约束

标签 ios swift uitableview

我有一个带有嵌入式 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()})
}
}

enter image description here

最佳答案

我将此函数添加到嵌入式 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/

相关文章:

arrays - Swift:搜索包含数组内数字的数组索引的更好方法?

ios - 如何使用 xmpp 在 swift 中按日期对聊天消息进行分组?

objective-c - Objective-C : How to reload data in parent cell from subclass

ios - 如何知道是否使用 MGSwipeTableCell 删除了所有单元格

ios - 删除 TableView 中第一行顶部的空间

ios - 如何在Objective-C中播放来自url的音频

ios - 在代码中使用静态单元格重新排序 UITableview

ios - EXC_BAD_ACCESS 当安全地展开 NSManagedObject 上的可选内容时

ios - 在 Swift 中打印当前文件的类名

ios - 节点的位置在物理模拟过程中保持不变