[英]Subclass ViewController from Storyboard
I created ViewController in Storyboard and I am using 我在Storyboard中创建了ViewController,我正在使用它
instantiateViewControllerWithIdentifier:
to load it. 加载它。 But I need to have this VC as base class and use 3-4 subclasses to change its properties.
但我需要将此VC作为基类,并使用3-4个子类来更改其属性。
How can I get an instance of my subclass with instantiateViewControllerWithIdentifier
? 如何使用
instantiateViewControllerWithIdentifier
获取我的子类的instantiateViewControllerWithIdentifier
?
@Bhagyesh version in Swift 3 : Swift 3中的 @Bhagyesh版本:
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
}
You will have to use object c runtime. 您将不得不使用对象c运行时。 Override init method of your subclass.
覆盖子类的init方法。 Create a BaseViewController object using 'instantiateViewControllerWithIdentifier'.
使用'instantiateViewControllerWithIdentifier'创建一个BaseViewController对象。 Then set the class for created object using objc_setClass method.
然后使用objc_setClass方法为创建的对象设置类。 Following code will go into SubclassViewController.m.
以下代码将进入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]. 在此之后,您可以使用简单的[[SubclassViewController alloc] init]创建SubclassViewController对象。
Just cast it. 只是施展它。
MyController *controller = (MyController *)[self.storyboard instantiateViewControllerWithIdentifier:@"myController"];
or Swift: 或斯威夫特:
let controller = storyboard?.instantiateViewControllerWithIdentifier("myController") as! MyController
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.