How do I set the height of tableHeaderView (UITableView) with autolayout?

后端 未结 12 1266
后悔当初
后悔当初 2020-11-27 10:23

I\'m been smashing my head against the wall with this for last 3 or 4 hours and I can\'t seem to figure it out. I have a UIViewController with a full screen UITableView insi

12条回答
  •  没有蜡笔的小新
    2020-11-27 11:08

    I really battled with this one and plonking the setup into viewDidLoad didn't work for me since the frame is not set in viewDidLoad, I also ended up with tons of messy warnings where the encapsulated auto layout height of the header was being reduced to 0. I only noticed the issue on iPad when presenting a tableView in a Form presentation.

    What solved the issue for me was setting the tableViewHeader in viewWillLayoutSubviews rather than in viewDidLoad.

    func viewWillLayoutSubviews() {
            super.viewWillLayoutSubviews()
            if tableView.tableViewHeaderView == nil {
                let header: MyHeaderView = MyHeaderView.createHeaderView()
                header.setNeedsUpdateConstraints()
                header.updateConstraintsIfNeeded()
                header.frame = CGRectMake(0, 0, CGRectGetWidth(tableView.bounds), CGFloat.max)
                var newFrame = header.frame
                header.setNeedsLayout()
                header.layoutIfNeeded()
                let newSize = header.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize)
                newFrame.size.height = newSize.height
                header.frame = newFrame
                self.tableView.tableHeaderView = header
            }
        }
    

提交回复
热议问题