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

前端 未结 29 1416
醉梦人生
醉梦人生 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:41

    I encountered the problem of getting width 375pt, the only way that worked for me is to relayout the tableView to get the correct width. I also preferred AutoLayout over setting Frame size.

    Here's the version that works for me:

    Xamarin.iOS

    public static void AutoLayoutTableHeaderView(this UITableView tableView, UIView header)
    {
        tableView.TableHeaderView = header;
        tableView.SetNeedsLayout();
        tableView.LayoutIfNeeded();
        header.WidthAnchor.ConstraintEqualTo(tableView.Bounds.Width).Active = true;       
        tableView.TableHeaderView = header;
    }
    

    Swift Version (modified from @Ben Packard answer)

    extension UITableView {
        //set the tableHeaderView so that the required height can be determined, update the header's frame and set it again
        func setAndLayoutTableHeaderView(header: UIView) {
            self.tableHeaderView = header
            self.setNeedsLayout()
            self.layoutIfNeeded()
            header.widthAnchor.widthAnchor.constraint(equalTo: self.bounds.width).isActive = true
            self.tableHeaderView = header
        }
    }
    

提交回复
热议问题