I've static functions to instantiate view controllers that look like
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!
}
}
I've a bunch of them so I'd like to make that cleaner as:
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 {
}
But I don't know of to dynamically refer to the type of the object in a static / class function, and how to have this refer to the subclass when called from a subclass. It's easy to do once an object has been instantiated with type(of: object)
Try this:
class MYViewController: UIViewController {
class func instantiate() -> Self {
let storyboard = UIStoryboard(name: "\(self)", bundle: nil)
let controller = storyboard.instantiateInitialViewController() as! Self
return controller
}
}
I'm not 100% sure it works because I didn't test your code directly (don't want to create a storyboard just for testing), but I wrote similar code to test it, which works:
class MYViewController: UIViewController {
class func instantiate() -> Self {
print("type: \(self)")
return self.init()
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With