简体   繁体   中英

How do I access the viewControllers on the UITabbarController in swift?

I'm trying to get the 2nd viewcontroller of the tabbarcontroller so i can popToRoot but Swift tells me that using an Int as a subscript is not valid and I have to use an AnyObject as an index

var controller = self.viewControllers[2] as! UIViewController

error is "Cannot subscript a value of type [AnyObject]? with an Int"

var controller = self.viewControllers![2] as! UIViewController

viewcontrollers 数组是从零开始的,所以第一个控制器的索引是 0,第二个是 1 所以对于第二个控制器,代码应该是

var controller = self.viewControllers![1] as! UIViewController

要获取实际的 ViewController 实例:

var controller = self.viewControllers![0].childForScreenEdgesDeferringSystemGestures

If you have a UIViewController nested in a UINavigationController :

if let destNav = viewControllers?[1] as? UINavigationController {
    if let destVC = destNav.children.first as? YourViewController {
        //do stuff
    }           
}

If you have multiple UINavigationControllers available, you have to test what index number to put in: viewControllers?[0] or viewControllers?[2] or whatever.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM