gpt4 book ai didi

ios - TabBarController 不会更改选定的索引

转载 作者:行者123 更新时间:2023-11-28 12:14:50 25 4
gpt4 key购买 nike

我正在尝试将选定的 tabBarItem(和 Controller)从索引 1 更改为索引 0。

这是我的代码:

  override func viewDidLoad() {

super.viewDidLoad()
self.tabBarController?.delegate = self


if UserDefaults.standard.double(forKey: "is_logged") != 1 {
// print always selectedIndex= Optional(0)
print("selectedIndex= \(self.tabBarController?.selectedIndex)")
self.tabBarController?.selectedIndex = 0
}

}

最佳答案

更新:这将不起作用,因为您的代码是在 tabbarController 的第二个(1 索引) Controller 中编写的。 UITabBarController 仅在启动时加载第一个(0 索引) Controller 。

最好的控制方法是在 UITabBarController 中创建 UITabBarController 的子类,并在它的 viewWillAppear 中执行类似这样的操作。

 /* viewWillAppear of TabBarController */
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)

/* Check if user logged in */
if UserDefaults.standard.double(forKey: "is_logged") != 1 {

// Select first index
self.selectedIndex = 0
} else {
/* User not logged in */

// Select second index
self.selectedIndex = 1
}
//Current selected index
print("selectedIndex = \(String(describing: self.selectedIndex))")
}

如果你想在 viewController 中执行此操作,那么在第一个 Controller 的 viewWillAppear 中执行如下操作

更新了以下代码

 /* viewWillAppear of FirstViewController */
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)

// check tabBarController is not nil
if self.tabBarController != nil {

/* Check if user logged in */
if UserDefaults.standard.double(forKey: "is_logged") != 1 {

// Select first index
self.tabBarController?.selectedIndex = 0

} else {
/* User not logged in */

// Select second index
self.tabBarController?.selectedIndex = 1
}
//Current selected index
print("selectedIndex = \(String(describing: self.tabBarController?.selectedIndex))")
} else {
print("tabBarController is nil :( ")
}
}

希望这会有所帮助:)

关于ios - TabBarController 不会更改选定的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47080278/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com