UITableViewHeaderFooterView subclass with auto layout and section reloading won't work well together

后端 未结 11 1291
天涯浪人
天涯浪人 2020-12-30 23:04

I am trying to incorporate auto layout into my UITableViewHeaderFooterView subclass. The class is pretty basic, just two labels. This is the complete subclass:



        
11条回答
  •  有刺的猬
    2020-12-31 00:03

    Working Solution as of iOS 9

    In your UITableViewHeaderFooterView subclass place the following code.

    - (void)setFrame:(CGRect)frame {
        if (frame.size.width == 0) {
            return;
        }
        
        [super setFrame:frame];
    }
    

    Explanation:

    The tableview handles the layout of the header views and it does so by manually manipulating the frames (yes even with autolayout turned on).

    If you inspect the width constraints that are on the header/footer views there are two, one contained on the superview (the table view) for the width, and one contained in the header/footer view itself for the width.

    The constraint contained on the super view is a NSAutoresizingMaskLayoutConstraint which is the giveaway that the tableview depends on frames to manipulate the headers. Switching the translatesAutoresizingMaskIntoConstraints to NO on the header view affectively breaks its appearance which is another give away.

    It appears that under some circumstances these header/footer views will have their frames change to a width of zero, for me it was when rows were inserted and the header views were reused. My guess is that somewhere in the UITableView code a preparation for an animation is made by starting the frame at zero width, even if you are not using an animation.

    This solution should work well and should not impact scroll performance.

提交回复
热议问题