简体   繁体   中英

Swift UITabBarController, save the order tab

Today I start practice how to use the UITabBarController. I have few tabs but notice when I see "More" (if I have 7 tabs), click edit to rearrange but notice when I close app and re-open the app, rearrange is gone. I believe it will not save the rearrange. I have UserDefaults.standard but couldn't figure how to save rearrange into my UserDefault.standard. I'm using Swift 4. Here my codes:

func create_tab_controller() {
   let first_view = UIViewController()
   first_view.tabBarItem.image = UIImage(systemName: "house", withConfiguration: main_symbol_configuration)
   first_view.tabBarItem.title = "Home"
   first_view.view.backgroundColor = UIColor.black

   let second_view = UIViewController()
   second_view.tabBarItem.image = UIImage(systemName: "rectangle", withConfiguration: main_symbol_configuration)
   second_view.tabBarItem.title = "Second View"
   second_view.view.backgroundColor = UIColor.darkGray

   let third_view = UIViewController()
   third_view.tabBarItem.image = UIImage(systemName: "gear", withConfiguration: main_symbol_configuration)
   third_view.tabBarItem.title = "Setting"
   third_view.view.backgroundColor = UIColor.gray

   main_tab_controller_order = [first_view, second_view, third_view]
   main_tab_controller.viewControllers = main_tab_controller_order
   view.addSubview(main_tab_controller.view)
}

Maybe I can point you to the general direction of what you can do:

  • Within the viewController which controls the UITabBarController, you can use

    main_tab_controller_order.delegate = self

    to sign up for the delegate methods of UITabbarController.

  • Then you need to implement the UITabbarDelegate protocol in your view controller

  • The UITabbarDelegate protocol contains a method called func tabBar(UITabBar, didEndCustomizing: [UITabBarItem], changed: Bool) . This method is called whenever you UITabbar is changed, ie also when the order of its view controllers changes.

  • Within this method, you can then save the order of view controllers to UserDefaults (for example as strings)

  • Then, on start of the application, read the value from UserDefaults and create your UITabbarController accordingly.

To elaborate on the UserDefaults part: You could iterate over all elements in main_tab_controller.view_controllers and for each controller in there, you could store it's class name as a string in UserDefaults. This might be the least complicated method to get you started.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM