Subclassing a subclassed UIViewController that has a xib

和自甴很熟 提交于 2019-12-19 06:16:08

问题


I need to have a few UIViewControllers that look very similar yet have different behaviours, so I thought I'd make a general UIViewController subclass with a xib, then subclass it when I need to, for those different UIViewController's that look alike.

I'm trying to achieve the following

UIViewController subclass (that has a xib file associated) -> and being able to subclass it as many times as i'd like (without additional xib files for the children)

what I've done so far :

xib file represents a UIViewController with multiple UI Elements.

I've set all the connections to file's owner @ xib file.

the subclass with the xib contains this @ init method:

self = [[[NSBundle mainBundle] loadNibNamed:
                 [NSString stringWithFormat:@"ParentViewController"]
                                              owner:self options:nil] objectAtIndex:0];

when I connect the View property in the xib to file's owner I get an exception saying I can't have the View property connected to both parent and child UIViewControllers.

yet when the View property is only connected to the UIViewController that the xib is associated with, I get a blank screen, and that outlet isn't disconnectable.

If I instantiate the parent vc instead of the child, everything works fine, If everything is done programatically and not with a xib, also everything works fine.

since this UIViewController displays A LOT of UI elements, I'm trying to set it with a xib.

I just don't really understand how can I get the child ViewControllers to look like the parent's xib file and have their own additions and behaviours.


回答1:


If you only have an xib for the parent class (but none of the subclasses), you can just do this in your subclass init:

- (instancetype) init {
    if (self = [super initWithNibName:@"ParentViewController" bundle:nil]) {
      // init stuff for subclass
    }
    return self;
 }

Here's an example project:

https://github.com/annabd351/SubClassFromParentNib




回答2:


If someone is looking for a Swift solution, you can use Convenience initializers on the subclass and initialise it using the super class xib.

In your subclass use the convenience initializer as:

class ChildController: BaseViewController {

    convenience init() {
        self.init(nibName: "BaseViewControllerXib", bundle: nil)
    }

    override func viewDidLoad() {
        super.viewDidLoad()
    }
}

And then when creating the child class object just use.

let childViewController = ChildController()
navigationController.pushViewController(childViewController, animated: true)

This way you can use the xib from the parent viewController.



来源:https://stackoverflow.com/questions/27336730/subclassing-a-subclassed-uiviewcontroller-that-has-a-xib

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!