I have a UIViewController
subclass as a scene in the storyboard that contains a UIScrollView
containing various subviews. One of the subviews is a
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.