如何使用Swift访问tabBarController中的ObjectAtIndex?
我曾经在obj-c中说过
[self.tabBarController.viewControllers objectAtIndex:1];
但现在在swift中没有ObjectAtIndex了
self.tabBarController.viewControllers.ObjectAtIndex
更新
好的,我会让它简单的让我们考虑我有tabBarController它包含2个对象[FirstViewController,SecondViewController],我想做一个委托之间的对象这里是代码来设置委托
var Svc:SecondViewController = self.tabBarController.viewControllers[1] as SecondViewController! Svc.delegate = self
当我运行,我得到这个错误0x1064de80d:movq%r14,%rax和没有控制台错误显示
你的代码是确定的:
var svc:SecondViewController = self.tabBarController.viewControllers[1] as SecondViewController! svc.delegate = self
…但是你可以省略!
标记在最后:SecondViewController
types定义,因为它可以被cast推断出来:
var svc = self.tabBarController.viewControllers[1] as SecondViewController
出现这个问题的原因是您尝试投射到错误的类。 尝试在[1]
打印debugging对象类的日志名称; 添加此之前,您的转换检查类名称:
let vcTypeName = NSStringFromClass(self.tabBarController.viewControllers[1].classForCoder) println("\(vcTypeName)")
更新:
正如我们在注释中想到的那样,您应该将接收到的视图控制器转换为UINavigationController
:
var nc = self.tabBarController.viewControllers[1] as UINavigationController
后来你可以检查nc.viewControllers
属性,看看它的topViewController
是否是SecondViewController
:
if nc.topViewController is SecondViewController { var svc = nc.topViewController as SecondViewController // your code goes here }
在swift中不需要objectAtIndex
,只需使用subscript
运算符:
self.tabBarController.viewControllers[1]
- Xcode:模拟器显示正确的xib界面,但在设备上,它显示旧界面
- IOS JSON反序列化失败 – STIG / NSJSONSerializer
- 如何检查rtmp或hlsurl是否存在或他们会给迅速404错误
- IOS:CS193p fall2013任务2:添加一个button让用户重新启动游戏
- 使用Swift 4.1.2编译的模块无法在Swift 4.1.50中导入:Xcode 10 Error
- iOS的libsystem_c.dylib strdup内存泄漏NSZombie无法正常工作
- 使用Avplayer在后台播放video
- 更新parsingsdk时出现许多错误
- 将两个具有相同名称的.swift文件添加到项目中