Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/119.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios Swift如何检查TabBarController中的ViewController是否为特定类_Ios_Swift_Uiviewcontroller_Uitabbarcontroller - Fatal编程技术网

Ios Swift如何检查TabBarController中的ViewController是否为特定类

Ios Swift如何检查TabBarController中的ViewController是否为特定类,ios,swift,uiviewcontroller,uitabbarcontroller,Ios,Swift,Uiviewcontroller,Uitabbarcontroller,我想确定TabBarController的第一个VC是否是SearchVC,如果是,则在启动时加载第二个VC。我创建了TabBarController的子类,并在viewDidLoad方法中尝试了以下操作: if let first = self.viewControllers?[0] as? SearchVC{ self.selectedIndex = 1 }else{ self.selectedIndex = 0 } 及 第一个控制器是SearchVC,当它应该是1时,它返

我想确定TabBarController的第一个VC是否是SearchVC,如果是,则在启动时加载第二个VC。我创建了TabBarController的子类,并在viewDidLoad方法中尝试了以下操作:

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

第一个控制器是SearchVC,当它应该是1时,它返回0
编辑:如果self.viewControllers?[0].isKindof:SearchVC不工作

这是协议和协议一致性的一个很好的用例

首先,您可以创建如下协议:

protocol TabBarInitial { }
这不需要变量或函数

接下来,让您的SearchVC符合它:

class SearchVC: TabBarInitial { ... }
并测试协议一致性,同时使用三元值设置值:

selectedIndex = viewControllers.first is TabBarInitial ? 1 : 0

我错过了我的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
            }
        }

谢谢你的回答

请阅读swift中的===Operator,或者只需点击下面的链接,为什么我们要使用没有任何协议的协议?在这种情况下,只需要检查它的类型。@Ryan首先,如果需要,它可以在整个应用程序中重用,否则OP将不得不不断添加要测试的类。或者该类被重命名,或者OP希望将来使用不同的类。
if let firstNav = self.viewControllers?[0] as? UINavigationController{
            if let first = firstNav.viewControllers.first as? SearchVC{
                self.selectedIndex = 1
            }else{
                self.selectedIndex = 0
            }
        }