Subclass ViewController from Storyboard

2019-01-26 08:01发布

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?

3条回答
聊天终结者
2楼-- · 2019-01-26 08:22

@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
}
查看更多
Juvenile、少年°
3楼-- · 2019-01-26 08:29

Just cast it.

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

or Swift:

let controller = storyboard?.instantiateViewControllerWithIdentifier("myController") as! MyController
查看更多
太酷不给撩
4楼-- · 2019-01-26 08:31

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

查看更多
登录 后发表回答