【问题标题】:How to programmatically open certain tab of a view controller如何以编程方式打开视图控制器的某些选项卡
【发布时间】:2018-01-30 13:08:13
【问题描述】:

我正在编写一个代码,其中我有一个带有某些选项卡的视图控制器。解除警报后,我想自动打开第二个选项卡。为此,我在警报消失时发布了本地通知。此通知的观察者位于主视图控制器中,当调用此观察者时,会选择视图控制器的第二个选项卡。这是我的代码以便更好地理解:

vc.dismiss(animated: true, completion: { 
// vc is the view controller in which my custom alert is shown

NotificationCenter.default.post(name: NSNotification.Name.OpenConsumerTab, 
                                    object: ConsumerHomeTab.Stats.rawValue)
})

还有home view controller:(问题相关代码)

NotificationCenter.default.addObserver(self,
                                       selector: #selector(onOpenConsumerTabNotificationRecieved(notification:)),
                                       name: Notification.Name.OpenConsumerTab,
                                       object: nil)

@objc public func onOpenConsumerTabNotificationRecieved(notification: Notification) {

    if (notification.object as! Int == ConsumerHomeTab.Stats.rawValue)
    {
        selectedIndex = 1
    }
}

这是打开选项卡,但我得到的输出是这样的:(得到一个额外的黑条)

为什么会这样?也许它正在显示一个全新的主视图控制器(带有标签栏),但原因是什么?如果我错了,请纠正我,因为我是 iOS 的新手。

我尝试过的事情:

  • 获取根视图控制器(主视图控制器)并选择其 选项卡,但输出相同。

  • 使用弹出视图控制器,但它打开了第一个选项卡(索引 0),但我的 要求是打开第二个标签(索引 1)

【问题讨论】:

  • 你必须有一个 tabbarController 的对象,它不是关于 rootviewcontroller 它的 tabbar 然后你可以像这样设置 self.tabBarController.selectedIndex = 1;
  • 它不工作。

标签: ios swift tabs tabbed-view


【解决方案1】:

我认为通知中心也不需要,你可以在关闭那个VC时编写这段代码

关闭您的警报

 alert.dismissWithClickedButtonIndex(-1, animated: true)

改变视图控制器:

 self.tabBarController?.selectedIndex = selectedTabIndex 


 // selectedTabIndex is the index of ViewController which you want to select

【讨论】:

  • 还是一样的输出 :(
  • 但是你为什么要关闭整个 ViewController 只是关闭警报然后编写这段代码。
  • 据我所知,当您关闭 tab-bar Controller 的 ViewController 时,请不要这样做,因为 tab-bar Controller 会自动管理内存。
  • 实际上我显示的警报是在单独的 VC 上。当警报被解除时,相应的 VC 也应该被解除。否则只会显示黑屏。
【解决方案2】:

请使用 tabbarController 实例将选定的索引设置为,可能您没有使用 tabbar 控制器实例设置索引:

if let tababarController = self.window!.rootViewController as! UITabBarController? { tababarController.selectedIndex = 1
}

【讨论】:

  • 还是一样的输出 :(
猜你喜欢
  • 2013-10-08
  • 1970-01-01
  • 1970-01-01
  • 2011-12-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-14
相关资源
最近更新 更多