UIScrollView's origin changes after popping back to the UIViewController

后端 未结 17 2330
不知归路
不知归路 2020-12-07 16:50

I have a UIViewController subclass as a scene in the storyboard that contains a UIScrollView containing various subviews. One of the subviews is a

17条回答
  •  一整个雨季
    2020-12-07 17:07

    I used a combination of the different solutions posted everywhere on SO, and came up with this subclass:

    // Keeps track of the recent content offset to be able to restore the
    // scroll position when a modal viewcontroller is dismissed
    class ScrollViewWithPersistentScrollPosition: UIScrollView {
    
        // The recent content offset for restoration.
        private var recentContentOffset: CGPoint = CGPoint(x: 0, y: 0)
    
        override func willMove(toWindow newWindow: UIWindow?) {
            if newWindow != nil {
                // save the scroll offset.
                self.recentContentOffset = self.contentOffset
            }
            super.willMove(toWindow: newWindow)
        }
    
        override func didMoveToWindow() {
            if self.window != nil {
                // restore the offset.
                DispatchQueue.main.async(execute: {
                    // restore it
                    self.contentOffset = self.recentContentOffset
                })
            }
            super.didMoveToWindow()
        }
     }
    

    Tested on iOS 11.2 / Xcode 9.2.

提交回复
热议问题