From b3c36c312611cef1a2aa95fe2b03c32116d5855f Mon Sep 17 00:00:00 2001 From: CMK Date: Thu, 24 Jun 2021 19:58:17 +0800 Subject: [PATCH] feat: scroll to top if needs when tap tab --- .../Scene/MainTab/MainTabBarController.swift | 32 +++++++++++++++++-- 1 file changed, 30 insertions(+), 2 deletions(-) diff --git a/Mastodon/Scene/MainTab/MainTabBarController.swift b/Mastodon/Scene/MainTab/MainTabBarController.swift index f0ee0a7f..db409ce6 100644 --- a/Mastodon/Scene/MainTab/MainTabBarController.swift +++ b/Mastodon/Scene/MainTab/MainTabBarController.swift @@ -16,6 +16,8 @@ class MainTabBarController: UITabBarController { weak var context: AppContext! weak var coordinator: SceneCoordinator! + + var currentTab = Tab.home enum Tab: Int, CaseIterable { case home @@ -95,7 +97,9 @@ extension MainTabBarController { override func viewDidLoad() { super.viewDidLoad() - + + delegate = self + view.backgroundColor = .systemBackground let tabs = Tab.allCases @@ -196,6 +200,27 @@ extension MainTabBarController { } +// MARK: - UITabBarControllerDelegate +extension MainTabBarController: UITabBarControllerDelegate { + func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) { + os_log(.info, log: .debug, "%{public}s[%{public}ld], %{public}s: select %s", ((#file as NSString).lastPathComponent), #line, #function, viewController.debugDescription) + defer { + if let tab = Tab(rawValue: tabBarController.selectedIndex) { + currentTab = tab + } + } + guard currentTab.rawValue == tabBarController.selectedIndex, + let navigationController = viewController as? UINavigationController, + navigationController.viewControllers.count == 1, + let scrollViewContainer = navigationController.topViewController as? ScrollViewContainer else { + return + } + + scrollViewContainer.scrollToTop(animated: true) + } +} + + // HIG: keyboard UX // https://developer.apple.com/design/human-interface-guidelines/macos/user-interaction/keyboard/ extension MainTabBarController { @@ -307,7 +332,10 @@ extension MainTabBarController { guard let index = Tab.allCases.firstIndex(of: tab) else { return } let previousTab = Tab(rawValue: selectedIndex) selectedIndex = index - + if let tab = Tab(rawValue: index) { + currentTab = tab + } + if let previousTab = previousTab { switch (tab, previousTab) { case (.home, .home):