Subclass ViewController from Storyboard

后端 未结 3 935
野趣味
野趣味 2020-12-17 16:11

I created ViewController in Storyboard and I am using

instantiateViewControllerWithIdentifier:

to load it. But I need to have this VC as b

相关标签:
3条回答
  • 2020-12-17 16:33

    @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
    }
    
    0 讨论(0)
  • 2020-12-17 16:37

    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].

    0 讨论(0)
  • 2020-12-17 16:40

    Just cast it.

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

    or Swift:

    let controller = storyboard?.instantiateViewControllerWithIdentifier("myController") as! MyController
    
    0 讨论(0)
提交回复
热议问题