swift - 无法动态引用视图控制器的名称
问题描述
当实例化视图控制器时,我想动态引用故事板标识符根据条件配对的类。我可以在实例化时传递图像文字的字符串名称,但不能传递 viewController swift 类?我得到的错误是Cannot find type 'viewControllers' in scope
例如:
var tabImage: String?
var viewControllers: UIViewController?
let tabBarController = CBFlashyTabBarController()
tabBarController.viewControllers = filteredNavigation.map { arrayProperty -> UIViewController in
if (arrayProperty.navname == "View1") {
print("View1")
tabImage = "tab1"
viewControllers = ViewController1
}
else if (arrayProperty.navname == "View2") {
print("View2")
tabImage = "tab2"
viewControllers = ViewController2
}
然后我可以在实例化时传递条件的结果:
let controller = storyboard!.instantiateViewController(withIdentifier: String(arrayProperty.navigationid)) as! viewControllers
controller.view.backgroundColor = UIColor.white
controller.navigationItem.title = arrayProperty.navname
controller.tabBarItem = UITabBarItem(title: arrayProperty.navname, image: #imageLiteral(resourceName: tabImage!), tag: 0)
controllerArray.append(controller)
return controller
解决方案
在这一行:
let controller = storyboard!.instantiateViewController(withIdentifier: String(arrayProperty.navigationid)) as! viewControllers
Swift 需要在编译时为变量分配一个类型controller
。这种类型必须是明确的。
右侧的值as!
必须是类型名称。在这里,您给出了一个变量(因此它不是类型名称 - 正是错误消息告诉您的内容)并且您似乎期望在运行时更改该值,而类型必须在编译时确定。
简而言之,你试图做的事情不能那样做。
更重要的是,这段代码不会编译:
class ViewController1 : UIViewController {
}
var viewControllers : UIViewController?
viewControllers = ViewController1
这声明为对 .实例的viewControllers
引用(可选引用)。 是一个类,而不是一个实例,所以这会产生一个编译器错误:UIViewController
ViewController1
无法将“ViewController1.Type”类型的值分配给“UIViewController”类型
推荐阅读
- java - Android studio 条码读取
- amazon-web-services - 为 AWS Systems Manager 设置 SSL 以与 EC2 一起使用
- windows - 批量查找和替换括号之间的文本
- shell - 我的命令行/终端上的 [SIGINT] 是什么意思?
- php - Symfony:如何获取与 oneToMany 关系相关的所有用户帖子
- javascript - javascript 代码错误:未捕获的 ReferenceError:**** 未在 HTMLDivElement.onclick 中定义
- angular - 如何在 Angular 中通过 Angular Material 使用浏览器的表单数据值
- android - 在反应本机后台下载器中更改并发限制
- i2c - Rs485和I2C显示器一起使用
- python - Pandas - 根据 value_counts() 结果重新编码变量