【问题标题】:Swift UITabBarController, save the order tabSwift UITabBarController,保存订单标签
【发布时间】:2020-09-18 08:46:28
【问题描述】:

今天我开始练习如何使用 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)
}

【问题讨论】:

  • 请用骆驼箱代替蛇箱,这样更快捷
  • 我认为只有某些类型的数据可以存储在 UserDefaults 中。我会存储一个纯字符串(可能是引用选项卡类型/名称),当您获得保存的 UserDefaults 字符串时,调用一个单独的函数(可能是 switch 语句)来确定每个选项卡类型/名称应该与什么相关联。

标签: ios swift delegates uitabbarcontroller nsuserdefaults


【解决方案1】:

也许我可以为您指明您可以做什么的大致方向:

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

    main_tab_controller_order.delegate = self

    注册UITabbarController的委托方法。

  • 那么你需要在你的视图控制器中实现UITabbarDelegate协议

  • UITabbarDelegate 协议包含一个名为func tabBar(UITabBar, didEndCustomizing: [UITabBarItem], changed: Bool) 的方法。每当您的 UITabbar 发生更改时,即当其视图控制器的顺序发生更改时,都会调用此方法。

  • 在此方法中,您可以将视图控制器的顺序保存到UserDefaults(例如作为字符串)

  • 然后,在应用程序启动时,从 UserDefaults 读取值并相应地创建您的 UITabbarController。

详细说明 UserDefaults 部分: 您可以遍历main_tab_controller.view_controllers 中的所有元素,并且对于其中的每个控制器,您可以将其类名作为字符串存储在 UserDefaults 中。这可能是让您入门的最简单的方法。

【讨论】:

  • 我只是用你的方法成功了,谢谢
猜你喜欢
  • 2017-04-29
  • 1970-01-01
  • 2018-08-21
  • 1970-01-01
  • 2023-03-23
  • 1970-01-01
  • 2015-10-01
  • 2011-07-15
  • 2011-08-04
相关资源
最近更新 更多