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

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

    I know this is an old post but After going through all the SO posts regarding this and passing a whole afternoon playing with this, I finally came up with a clean and yet very simple solution

    First of all, My view hierarchy looks like this:

    1. Table View
      1. View tableHeaderView
        1. View with an outlet called headerView

    Now inside the View (No.3), I set up all the constraints as I would normally including the bottom space to container. This will make the container (i.e. 3.View i.e. headerView) to size itself based on it's subviews and their constraints.

    After that, I set the constraints between 3. View and 2. View to these:

    1. Top Space to container: 0
    2. Leading Space to container: 0
    3. Trailing Space to container: 0

    Notice that I omit intentionally the bottom space intentionally.

    Once all of this is done in the storyboard, everything that's left to do is paste those three lines of codes:

    if (self.headerView.frame.size.height != self.tableView.tableHeaderView.frame.size.height) {
        UIView *header = self.tableView.tableHeaderView;
        CGRect frame = self.tableView.tableHeaderView.frame;
        frame.size.height = self.headerView.frame.size.height + frame.origin.y;
        header.frame = frame;
        self.tableView.tableHeaderView = header;
    }
    

提交回复
热议问题