我正在使用present
打开视图控制器。
self.storyboard = UIStoryboard(name: "myStoryboard", bundle: nil)
self.myView = self.storyboard?.instantiateInitialViewController() as? myViewController
self.present(self.myView!, animated: true) { _ in }
然后在视图控制器中我试图从初始化器
获取数据class myViewController: UIViewController {
var dataA: String?
var dataB: String?
override init(dataA: String, dataB: String) {
self.dataA = dataA
self.dataB = dataB
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
我收到错误Initializer does not override a designated initializer from its superclass
在这种情况下,如何覆盖init
并传递数据?
答案 0 :(得分:0)
除了不使用故事板之外,我认为没有办法。甚至Swinject也在一个单独的方法中做到这一点。
class myViewController: UIViewController {
var dataA: String?
var dataB: String?
fun initialize(dataA: String, dataB: String) {
self.dataA = dataA
self.dataB = dataB
}
}
并在另一个班级
self.storyboard = UIStoryboard(name: "myStoryboard", bundle: nil)
self.myView = self.storyboard?.instantiateInitialViewController() as? myViewController
self.myView.initialize(dataA: dataA, dataB: dataB)
self.present(self.myView!, animated: true) { _ in }
或者你可以用其他方式来创建一个静态函数,它将返回一个实例。但我更喜欢第一种方式。
class myViewController: UIViewController {
var dataA: String?
var dataB: String?
static func instance(dataA: String, dataB: String) -> myViewController {
//You could pass storyboard too
let storyboard = UIStoryboard(name: "myStoryboard", bundle: nil)
let myView = storyboard.instantiateInitialViewController() as? myViewController
self.dataB = dataB
self.dataA = dataA
return myView
}
}