【问题标题】:Programatically change selected tab for IOS using Swift使用 Swift 以编程方式更改 IOS 的选定选项卡
【发布时间】:2021-08-13 18:21:14
【问题描述】:

我对这个有点坚持,

我的应用上有一个注销按钮,当我点击它时,我想将标签栏控制器的选定标签更改为应用加载时选择的标签(索引 0)(这应该会触发“登录继续”视图)

更多上下文

我的应用程序的根视图是TabBarController,每个选项卡的声明如下:

let friends = CalendarNavigationController(rootViewController: FriendsListViewController())
    friends.title = "Friends"
    friends.tabBarItem.image = UIImage(named: "icon_friends")

这是我想在注销后发送给用户的地方,以触发WelcomeViewController

let myMonth = CalendarNavigationController(rootViewController: CalendarViewController())
myMonth.title = "My Month"
myMonth.tabBarItem.image = UIImage(named: "icon_me")

控制器分配有这条线:viewControllers = [myMonth, friends, notification, more]

注销按钮位于 UserManagerViewController 内,它以模态方式从 SettingsViewController 呈现(在标签栏中被命名为 "more" 很糟糕)

(差不多了)

点击时按钮成功调用该函数:

@objc func doLogout(){
    print("Logout")
    do {
       // try  Auth.auth().signOut()
        self.dismiss(animated: true) {
            print(self.parent?.tabBarController) <--- This is nil
            self.parent?.tabBarController?.selectedViewController = self.parent?.tabBarController?.viewControllers![0]
            
        }
    } catch {
        
    }
}

我已经尝试过.selectedViewController(从我的代码中可以看到)和.selectedIndex[0]...据我所知,似乎没有任何事情发生,大概是因为self.parent?.tabBarController 似乎为零。

有没有人知道我哪里出错了,或者我如何才能完成这项工作?

谢谢:)

【问题讨论】:

  • 我猜这是因为 self.parent 似乎为零。你能告诉我你是如何设置父母的吗?
  • 我同意评论和答案所暗示的内容(他们是两个不同的人)。我所看到的 - 听起来两者都在说 - 你并没有真正针对 actual 视图控制器层次结构进行编码。很难从您发布的代码中复制出来,但听起来它是一个标签栏 VC,它呈现两个(或更多)VC 之一,其中一个呈现注销 VC。如果这是正确的,您需要一种方法让注销 VC 与选项卡栏 VC 一起使用,可能是直接使用。正如发布的那样,这就是您需要授权的原因。
  • @PrateekVarshney 和 dfd 这很有意义,我偶尔(现在无法复制它)在日志上收到一条消息,关于推送不属于视图层次结构的视图(在我的待办事项列表中)最终地址)...这可能是这里发生的事情,我怀疑这将是另一个问题哈哈,同时我会尝试 Sh_Khan 的答案:)

标签: ios swift


【解决方案1】:

你可以试试

@objc func doLogout(){
    print("Logout")
    do {
        try  Auth.auth().signOut()
        self.dismiss(animated: true) {
            if let tab = (UIApplication.shared.delegate as! AppDelegate).window?.rootViewController as? UITabBarController {
               tab.selectedIndex = 0 
            }
        }
    } catch {
        
    }
}

【讨论】:

  • 谢谢!我不知道如何访问代表! (将在不久的将来有用)并且您的答案完美无缺! :)
猜你喜欢
  • 2011-06-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-01
  • 1970-01-01
  • 2016-12-03
  • 1970-01-01
  • 2021-12-08
相关资源
最近更新 更多