我有静态函数来实例化看起来像
的视图控制器class AController: UIViewController {
static func instantiate() -> AController {
let storyboard = UIStoryboard(name: "AController", bundle: nil)
let controller = s.instantiateInitialViewController() as? AController
return controller!
}
}
class BController: UIViewController {
static func instantiate() -> BController {
let storyboard = UIStoryboard(name: "BController", bundle: nil)
let controller = storyboard.instantiateInitialViewController() as? BController
return controller!
}
}
我有很多他们所以我想把它变得更清洁:
class MYViewController: UIViewController {
class func instantiate() -> self.type {
let storyboard = UIStoryboard(name: "\(self.type)", bundle: nil)
let controller = storyboard.instantiateInitialViewController() as? self.type
return controller!
}
}
class AController: MYViewController {
}
class BController: MYViewController {
}
但我不知道动态引用static / class函数中对象的类型,以及如何从子类调用时引用它。一旦使用type(of: object)
答案 0 :(得分:0)
试试这个:
class MYViewController: UIViewController {
class func instantiate() -> Self {
let storyboard = UIStoryboard(name: "\(self)", bundle: nil)
let controller = storyboard.instantiateInitialViewController() as! Self
return controller
}
}
我不是百分之百确定它是否有效,因为我没有直接测试你的代码(不想仅仅为了测试而创建一个故事板),但是我编写了类似的代码来测试它,它起作用:
class MYViewController: UIViewController {
class func instantiate() -> Self {
print("type: \(self)")
return self.init()
}
}