首页 > 解决方案 > 无法动态引用视图控制器的名称

问题描述

当实例化视图控制器时,我想动态引用故事板标识符根据条件配对的类。我可以在实例化时传递图像文字的字符串名称,但不能传递 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

标签: swift

解决方案


在这一行:

let controller = storyboard!.instantiateViewController(withIdentifier: String(arrayProperty.navigationid)) as! viewControllers

Swift 需要在编译时为变量分配一个类型controller。这种类型必须是明确的。

右侧的值as!必须是类型名称。在这里,您给出了一个变量(因此它不是类型名称 - 正是错误消息告诉您的内容)并且您似乎期望在运行时更改该值,而类型必须在编译时确定。

简而言之,你试图做的事情不能那样做。

更重要的是,这段代码不会编译:

class ViewController1 : UIViewController {
}

var viewControllers : UIViewController?

viewControllers = ViewController1

这声明为对 .实例viewControllers引用(可选引用)。 是一个,而不是一个实例,所以这会产生一个编译器错误:UIViewControllerViewController1

无法将“ViewController1.Type”类型的值分配给“UIViewController”类型


推荐阅读