Subclass ViewController from storyboard

I created a ViewController in a Storyboard and I use

instantiateViewControllerWithIdentifier: 

to download it. But I need this VC to be a base class and use 3-4 subclasses to change its properties.

How can I get an instance of my subclass with instantiateViewControllerWithIdentifier ?

+4
source share
3 answers

You will need to use the runtime of the object c. Override the init method of your subclass. Create a BaseViewController object using the 'instantiateViewControllerWithIdentifier'. Then set the class for the created object using the objc_setClass method. The following code will go to 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 that, you can simply create the SubclassViewController object using the simple [[SubclassViewController alloc] init].

+2
source

@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 } 
+1
source

Just drop it.

 MyController *controller = (MyController *)[self.storyboard instantiateViewControllerWithIdentifier:@"myController"]; 

or Swift:

 let controller = storyboard?.instantiateViewControllerWithIdentifier("myController") as! MyController 
-1
source

Source: https://habr.com/ru/post/1445901/


All Articles