【发布时间】:2015-03-19 10:18:20
【问题描述】:
我想初始化一个在运行时指定的类的实例。我有以下设置。
//MyClass1 & MyClass2 inherit from UIViewController
let arr = MyClass1.self,MyClass2.self]
func didSelectRow(index:Int) {
var controllerRef = arr[index] //This returns a .Type
var controllerClass = controllerRef() //This returns “the class” MyClass1
//This is where I'm stuck. How do I initialize controller??
//Finally, push VC
self.navigationController?.pushViewController(controller, animated: true)
}
要使用 Objective C 初始化 VC,我可以这样做:
UIViewController *controller = [((UIViewController *)[controllerClass alloc]) initWithNibName:class1Nib bundle:nil];
对于 Swift,我期待类似下面的语法,但它不起作用
//Doesn’t work
var controller = (controllerClass as UIViewController)(nibName: class1Nib, bundle:nil)
//Overriding the init method in MyClass1 and then calling the below doesn’t work
var controller = controllerClass(nibName: class1Nib, bundle:nil)
//The below works, but viewDidLoad() does not get called. It only loads the nib file
var controller = UIViewController(nibName: Class1Nib, bundle:nil)
感谢任何帮助。谢谢
【问题讨论】:
-
这是关于 nib 文件还是关于按其类实例化视图控制器?
-
这不是代码:
let arr = MyClass1.self,MyClass2.self]在 Stack Overflow 上提问时需要提供真实代码。 -
这是关于实例化视图控制器的。对不起,我已经编辑了标题。这是真实的代码,我不必提供真实的类名和变量 - 有无数的帖子包含 FooBar 示例。
标签: ios swift uiviewcontroller xib nib