簡體   English   中英

無法使用self.tabBarController?.selectedIndex更改選項卡

[英]Unable to change tab using self.tabBarController?.selectedIndex

我的應用程序嵌入在TabBarController ,我試圖從ViewController切換選定的選項卡。

通過以下幾行,我希望找出這個功能是否有效,不幸的是它沒有,但我不確定為什么,任何人都可以幫助我出錯的地方?

func tabbar() { self.tabBarController?.selectedIndex = 4 }

override func viewDidLoad() {
    super.viewDidLoad()
    tabbar()

}

PS:我測試這個的原因是因為我想知道以下內容是否適用於我的3DTouchShortcuts 我知道3D觸摸快捷鍵出現並打開初始視圖控制器,我希望每個案例的以下行實際上會使快捷方式打開到不同的選項卡。

tababarController.selectedIndex = 1

private func handleShortcutItem(shortcutItem: UIApplicationShortcutItem) {

     if let rootViewController = window?.rootViewController, let shortcutItemType = ShortcutItemType(shortcutItem: shortcutItem) {
        let tabbarController = rootViewController as! UITabBarController

        switch shortcutItemType {
        case .AddItem:
            NSNotificationCenter.defaultCenter().postNotificationName("performsegueAddItem", object: nil)
            tabbarController.selectedIndex = 1
            break
        case .FavouritesTab:
            tabbarController.selectedIndex = 2
            break

        }
    }
}

你只需要在viewDidLayoutSubviews而不是viewDidLoad調用它,你應該在調用它時使用tabBarController 您還應該使用guard來打開它:

override func viewDidLayoutSubviews() {
    guard let tabBarController = tabBarController else { return }
    tabBarController.selectedIndex = 0
}

更容易

override func viewWillAppear(_ animated: Bool) {
    self .selectedIndex = 2 // desired index
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM