【问题标题】:Swift How to check if ViewController in TabBarController is a particular classSwift如何检查TabBarController中的ViewController是否是一个特定的类
【发布时间】:2017-10-25 16:51:09
【问题描述】:

我想确定 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()) 也不起作用

【问题讨论】:

标签: ios swift uiviewcontroller uitabbarcontroller


【解决方案1】:

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

感谢您的回答!

【讨论】:

    【解决方案2】:

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

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

    protocol TabBarInitial { }
    

    不需要任何变量或函数。

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

    class SearchVC: TabBarInitial { ... }
    

    并在使用三元组设置值时测试协议一致性:

    selectedIndex = viewControllers.first is TabBarInitial ? 1 : 0
    

    【讨论】:

    • 我们为什么要使用没有protocolprotocol?在这种情况下只需要检查它的类型。
    • @Ryan 一方面,如果需要,它可以在整个应用程序中重用,否则 OP 将不得不不断添加要测试的类。或者类被重命名,或者 OP 想在未来使用不同的类。
    猜你喜欢
    • 2017-12-09
    • 1970-01-01
    • 2017-07-03
    • 1970-01-01
    • 2017-11-06
    • 2020-06-07
    • 2023-03-10
    • 1970-01-01
    • 2014-11-02
    相关资源
    最近更新 更多