@@ -15,23 +15,33 @@ class RootTabBarController: UITabBarController, UITabBarControllerDelegate {
1515 }
1616
1717 func tabBarController( _ tabBarController: UITabBarController , didSelect viewController: UIViewController ) {
18- if let splitViewController = viewController as? UISplitViewController {
19- if let navigationController = splitViewController. viewControllers. last as? UINavigationController {
20- if navigationController. viewControllers. count > 1 {
21- navigationController. popViewController ( animated: true )
18+ guard
19+ let splitViewController = viewController as? UISplitViewController ,
20+ let navigationController = splitViewController. viewControllers. last as? UINavigationController
21+ else {
22+ return
23+ }
24+
25+ // if several view controllers are in the stack, pop to the root
26+ if navigationController. viewControllers. count > 1 {
27+ navigationController. popToRootViewController ( animated: true )
28+ } else {
29+ // if there's at least one view controller in the stack (which there always should be)
30+ if let firstController = navigationController. viewControllers. first {
31+ // we either delegate to the controller since it knows better how to scroll to the top
32+ if let scrollableToTop = firstController as? ScrollableToTop {
33+ scrollableToTop. scrollAfterTabTap ( )
34+ // or we find the topmost scroll view and scroll it to the top
2235 } else {
23- navigationController . viewControllers . first ? . scrollToTop ( )
36+ firstController . view . findScrollSubview ( ) ? . setContentOffset ( . zero , animated : true )
2437 }
2538 }
2639 }
2740 }
2841}
2942
30- private extension UIViewController {
31- func scrollToTop( ) {
32- let scrollView = view. findScrollSubview ( )
33- scrollView? . setContentOffset ( . zero, animated: true )
34- }
43+ protocol ScrollableToTop {
44+ func scrollAfterTabTap( )
3545}
3646
3747private extension UIView {
0 commit comments