How to access ObjectAtIndex in tabBarController with Swift?

后端 未结 2 547
遥遥无期
遥遥无期 2021-02-14 03:08

i used to say in obj-c

[self.tabBarController.viewControllers objectAtIndex:1];

but now in swift no ObjectAtIndex any more

sel         


        
2条回答
  •  北恋
    北恋 (楼主)
    2021-02-14 03:42

    Your code is OK:

    var svc:SecondViewController = self.tabBarController.viewControllers[1] as SecondViewController!
    svc.delegate = self
    

    ... however you can omit ! mark at the end and :SecondViewController type definition since it can be inferred by the cast:

    var svc = self.tabBarController.viewControllers[1] as SecondViewController
    

    The problem appears because you try to cast to the wrong class. Try to print to debug log name of the class of object at [1]; add this before your cast to check the class name:

    let vcTypeName = NSStringFromClass(self.tabBarController.viewControllers[1].classForCoder)
    println("\(vcTypeName)")
    

    UPDATE:

    As we figured out in comments, you should cast received view controller to UINavigationController:

    var nc = self.tabBarController.viewControllers[1] as UINavigationController
    

    Later you can examine nc.viewControllers property and see if for instance its topViewController is SecondViewController:

    if nc.topViewController is SecondViewController {
        var svc = nc.topViewController as SecondViewController
        // your code goes here
    }
    

提交回复
热议问题