Search code examples
iosuiviewuiscrollviewuikitlayoutsubviews

UIScrollView - detecting scrolling vs orientation change in layoutSubviews?


Question - In the "layoutSubviews" callback of a custom UIScrollView how could one detect the different of scrolling (which may not require subview re-layout) with other events such as an orientation change (which does require re-layout)?

Background - I want to add/remove subviews programmatically as scrolling occurs but in this case the existing views on the scrollview don't need re-layout, so I don't want to go through all these calculations. However when an event such as orientation-change occurs I do want to recalc all positions. So my question is aimed at finding the best approach to handle this. In this case I do not want to use UIContainerView by the way.


Solution

  • let priorLayoutSize = CGSize.zero
    
    func layoutSubviews() {
        super.layoutSubviews()
    
        let layoutSize = bounds.size
        if layoutSize != priorLayoutSize {
            priorLayoutSize = layoutSize
            // do full layout
        } else {
            // do incremental layout
        }
    }