Is it possible to use AutoLayout with UITableView's tableHeaderView?

前端 未结 29 1450
醉梦人生
醉梦人生 2020-11-28 19:51

Since I discovered AutoLayout I use it everywhere, now I\'m trying to use it with a tableHeaderView.

I made a subclass of

29条回答
  •  余生分开走
    2020-11-28 20:35

    An old post. But a good post. Here's my 2 cents.

    Firstly, ensure that your header view has its constraints arranged so that it can support it's own intrinsic content size. Then do the following.

    //ViewDidLoad
    headerView.translatesAutoresizingMaskIntoConstraints = false
    headerView.configure(title: "Some Text A")
    
    //Somewhere else
    headerView.update(title: "Some Text B)
    
    private var widthConstrained = false
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        if widthConstrained == false {
            widthConstrained = true
            tableView.addConstraint(NSLayoutConstraint(item: headerView, attribute: .width, relatedBy: .equal, toItem: tableView, attribute: .width, multiplier: 1, constant: 0))
            headerView.layoutIfNeeded()
            tableView.layoutIfNeeded()
        }
    }
    
    override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
        super.viewWillTransition(to: size, with: coordinator)
        coordinator.animate(alongsideTransition: { (context) in
            self.headerView.layoutIfNeeded()
            self.tableView.layoutIfNeeded()
        }, completion: nil)
    }
    

提交回复
热议问题