Swift 为 UITableView 中的容器视图设置约束

Swift set constraints to container view in UITableView

我有 UITableView,我将容器视图作为 header 放在顶部,如下所示:

一切正常。

现在我想在点击单元格时隐藏此容器 header 视图。

我的第一次尝试是:

UIView.animate(withDuration: 0.3, animations: {
    self.containerView.frame.size.height = 0
})

隐藏视图,但不显示单元格,这是预期的和正常的,因为我只更改容器视图的框架,而不是其他视图。

然后我尝试在故事板中添加约束,但由于某些原因我无法设置它们。

这是为什么?以及如何实现隐藏容器视图,并将所有其他单元格置于顶部。

试试这个

UIView.animate(withDuration: 0.5) {
            let headerView = tableView.tableHeaderView!
            headerView.setNeedsLayout()
            headerView.layoutIfNeeded()
            headerView.frame.size.height = 0
            tableView.tableHeaderView = headerView
        }