如何使用Swift访问tabBarController中的ObjectAtIndex?

Amr*_*med 11 uitabbarcontroller viewcontroller ios swift

我以前在obj-c中说过

[self.tabBarController.viewControllers objectAtIndex:1];
Run Code Online (Sandbox Code Playgroud)

但现在快速没有ObjectAtIndex了

self.tabBarController.viewControllers.ObjectAtIndex
Run Code Online (Sandbox Code Playgroud)

更新

好吧我会让它变得简单让我认为我有tabBarController它包含2个对象[FirstViewController,SecondViewController],我试图在这里的对象之间建立委托是设置委托的代码

var Svc:SecondViewController = self.tabBarController.viewControllers[1] as SecondViewController!
Svc.delegate = self
Run Code Online (Sandbox Code Playgroud)

当我运行时,我收到此错误0x1064de80d:movq%r14,%rax并且没有出现控制台错误

Kee*_*nle 21

你的代码没问题:

var svc:SecondViewController = self.tabBarController.viewControllers[1] as SecondViewController!
svc.delegate = self
Run Code Online (Sandbox Code Playgroud)

...但是你可以省略!末尾的标记和:SecondViewController类型定义,因为它可以由演员推断:

var svc = self.tabBarController.viewControllers[1] as SecondViewController
Run Code Online (Sandbox Code Playgroud)

出现问题是因为您尝试强制转换为错误的类.尝试打印调试对象类的日志名称[1]; 在演员表之前添加此项以检查班级名称:

let vcTypeName = NSStringFromClass(self.tabBarController.viewControllers[1].classForCoder)
println("\(vcTypeName)")
Run Code Online (Sandbox Code Playgroud)

更新:

正如我们在评论中指出的那样,您应该将接收到的视图控制器转换为UINavigationController:

var nc = self.tabBarController.viewControllers[1] as UINavigationController
Run Code Online (Sandbox Code Playgroud)

稍后你可以检查nc.viewControllers属性,看看它topViewController是否是SecondViewController:

if nc.topViewController is SecondViewController {
    var svc = nc.topViewController as SecondViewController
    // your code goes here
}
Run Code Online (Sandbox Code Playgroud)