Swift UITabBarController,保存订单标签。

问题描述 投票:0回答:1

今天我开始练习如何使用UITabBarController。我有几个标签页,但我注意到当我看到 "更多 "时(如果我有7个标签页),点击编辑来重新排列,但注意到当我关闭应用程序并重新打开应用程序时,重新排列已经消失了。我相信它不会保存重新排列。我有UserDefaults.standard,但不知道如何将重排保存到我的UserDefault.standard里。我使用的是Swift 4。这是我的代码。

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)
}
ios swift delegates uitabbarcontroller nsuserdefaults
1个回答
0
投票

也许我可以给你指出你可以做的大方向。

  • 在控制UITabBarController的viewController中,你可以使用:

    main_tab_controller_order.delegate = self

    来注册UITabbarController的委托方法。

  • 然后你需要实现UITabbarController的 UITabbarDelegate 视图控制器中的协议

  • UITabbarDelegate 协议中包含一个叫做 func tabBar(UITabBar, didEndCustomizing: [UITabBarItem], changed: Bool). 每当你的UITabbar被改变时,也就是当它的视图控制器的顺序改变时,这个方法就会被调用。

  • 在这个方法中,您可以将视图控制器的顺序保存到 UserDefaults (比如说)

  • 然后,在应用程序启动时,从 UserDefaults 并据此创建你的UITabbarController。

详述UserDefaults部分:你可以迭代所有元素,在 main_tab_controller.view_controllers 而对于其中的每个控制器,你可以将它的类名作为一个字符串存储在UserDefaults中。 这可能是最简单的入门方法。

© www.soinside.com 2019 - 2024. All rights reserved.