How to remember last selected tab in UITabBarController?

前端 未结 6 1637
小鲜肉
小鲜肉 2021-02-08 04:30

I\'m trying to make my app remember which tab was last being viewed before the app quit, so that the app opens up to the same tab when it is next launched. This is the functiona

6条回答
  •  北恋
    北恋 (楼主)
    2021-02-08 05:05

    Here is the Swift 3 solution. Just set the class of your TabBarController to RememberingTabBarController in the Storyboard

    import Foundation
    import UIKit
    
    class RememberingTabBarController: UITabBarController, UITabBarControllerDelegate {
        let selectedTabIndexKey = "selectedTabIndex"
    
        override func viewDidLoad() {
            super.viewDidLoad()
            self.delegate = self
    
            // Load the last selected tab if the key exists in the UserDefaults
            if UserDefaults.standard.object(forKey: self.selectedTabIndexKey) != nil {
                self.selectedIndex = UserDefaults.standard.integer(forKey: self.selectedTabIndexKey)
            }
        }
    
        func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) {
            // Save the selected index to the UserDefaults
            UserDefaults.standard.set(self.selectedIndex, forKey: self.selectedTabIndexKey)
            UserDefaults.standard.synchronize()
        }
    }
    

提交回复
热议问题