I am trying to write a small extension in Swift to handle an instance of a UIViewController from a storyboard.
My idea is this: UIStoryboard UIStoryboard instantiateViewControllerWithIdentifier method needs an identifier to instantiate this storyboard view controller, why not assign each view controller in my storyboard an identifier equal to its exact class name (that is, UserDetailViewController will have the identifier "UserDetailViewController") and create a method a class in a UIViewController that:
- accept an instance of
UIStoryboard as a unique parameter - get the current class name as a string
- calling
instantiateViewControllerWithIdentifier on the instantiateViewControllerWithIdentifier storyboard with the class name as parameter - get the newly created instance of the
UIViewController and return it
So instead (which repeats the class name as a string is not very nice)
let vc = self.storyboard?.instantiateViewControllerWithIdentifier("UserDetailViewController") as UserDetailViewController
it would be:
let vc = UserDetailViewController.instantiateFromStoryboard(self.storyboard!)
I used to do this in Objective-C with the following category:
+ (instancetype)instantiateFromStoryboard:(UIStoryboard *)storyboard { return [storyboard instantiateViewControllerWithIdentifier:NSStringFromClass([self class])]; }
But I am completely stuck in the Swift version. I hope there is some way to do this. I tried the following:
extension UIViewController { class func instantiateFromStoryboard(storyboard: UIStoryboard) -> Self { return storyboard.instantiateViewControllerWithIdentifier(NSStringFromClass(Self)) } }
Returning Self instead of AnyObject allows AnyObject with an output type. Otherwise, I would have to throw every return of this method, which is annoying, but maybe you have a better solution?
This gives me an error: Use of unresolved identifier 'Self' Part of the NSStringFromClass seems to be a problem.
What do you think?
Thank you
ios objective-c iphone uiviewcontroller swift
Nicolas B.
source share