簡體   English   中英

Swift如何檢查TabBarController中的ViewController是否為特定類

[英]Swift How to check if ViewController in TabBarController is a particular class

我想確定TabBarController的第一個VC是否為SearchVC,如果是,則在啟動時加載第二個VC。 我創建了TabBarController的子類,並在viewDidLoad()方法中嘗試了以下操作:

if let first = self.viewControllers?[0] as? SearchVC{
    self.selectedIndex = 1
}else{
    self.selectedIndex = 0
}

if self.viewControllers?[0] is SearchVC{
    self.selectedIndex = 1
}else{
    self.selectedIndex = 0
}

第一個控制器是SearchVC,當它應該是1時它返回0編輯:同樣, if self.viewControllers?[0].isKind(of: SearchVC())不起作用

我錯過了SearchVC控制器嵌入UINavigationController中的事實。 下面的代碼解決了我的問題:

if let firstNav = self.viewControllers?[0] as? UINavigationController{
            if let first = firstNav.viewControllers.first as? SearchVC{
                self.selectedIndex = 1
            }else{
                self.selectedIndex = 0
            }
        }

謝謝你的回答!

這是用於協議和協議一致性的好用例。

首先,您可以創建如下協議:

protocol TabBarInitial { }

為此,不需要任何變量或函數。

接下來,讓您的SearchVC符合它:

class SearchVC: TabBarInitial { ... }

並在使用三元數設置值的同時測試協議一致性:

selectedIndex = viewControllers.first is TabBarInitial ? 1 : 0

暫無
暫無

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

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