问题
I created ViewController in Storyboard and I am using
instantiateViewControllerWithIdentifier:
to load it. But I need to have this VC as base class and use 3-4 subclasses to change its properties.
How can I get an instance of my subclass with instantiateViewControllerWithIdentifier?
回答1:
@Bhagyesh version in Swift 3:
class func instantiateFromSuperclassStoryboard() -> SubclassViewController {
let stroryboard = UIStoryboard(name: "Main", bundle: nil)
let controller = stroryboard.instantiateViewController(withIdentifier: "BaseViewController")
object_setClass(controller, SubclassViewController.self)
return controller as! SubclassViewController
}
回答2:
You will have to use object c runtime. Override init method of your subclass. Create a BaseViewController object using 'instantiateViewControllerWithIdentifier'. Then set the class for created object using objc_setClass method. Following code will go into SubclassViewController.m.
- (instancetype)init {
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"main" bundle:[NSBundle mainBundle]];
UIViewController *baseClassViewController = [storyboard instantiateViewControllerWithIdentifier:@"baseClassIdentifier"];
object_setClass(baseClassViewController, [SubclassViewController class]);
return (SubclassViewController *)baseClassViewController;
}
After this, you can simply create SubclassViewController object using simple [[SubclassViewController alloc] init].
回答3:
Just cast it.
MyController *controller = (MyController *)[self.storyboard instantiateViewControllerWithIdentifier:@"myController"];
or Swift:
let controller = storyboard?.instantiateViewControllerWithIdentifier("myController") as! MyController
来源:https://stackoverflow.com/questions/32556072/subclass-viewcontroller-from-storyboard