Load custom UIView with XIB from a View Controller's view using IB

China☆狼群 提交于 2020-01-12 07:58:30

问题


I have a custom UIView (MyCustomUIView) which is built using Interface Builder. I'd like to place this custom view in MyViewController's view, which is also designed using IB. I've placed an UIView as a subview in MyViewController's XIB and set it's class to MyCustomUIView. The problem is, when I run the code, only a blank view appears. (When I instantiate MyCustomUIView in code, it displays well.)

I'm only overriding the initWithFrame: method the following way in MyCustomUIView.m:

- (id)initWithFrame:(CGRect)frame
{
    [[NSBundle mainBundle] loadNibNamed:@"MyCustomUIView" owner:self options:nil];
    self = self.view;
    return self;
}

What should I do to make the view load properly? How should initWithCoder: look like?


回答1:


You are correct. IB uses initWithCoder. initWithCoder should look very similar to your other init methods:

- (id)initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];
    if (self) {
        // CUSTOM INITIALIZATION HERE
    }
    return self;
}

Once you assign your class within IB, you won't need to instantiate it from the bundle unless I'm misunderstanding your intention.




回答2:


Do not put anything in the view part of the view controller in IB. Instead, set the nib name for the view controller in IB to the name of the nib containing the view. In the nib containing the view, set the file's owner to the view controller class and hook up its view property to the view.

The result will be that when the view controller is instantiated, if it is instantiated from the nib (which you have not proved is what's really going to happen, but let's just say it is), it will find the nib and load the view from it.

Basically the rule is that it makes no difference where a view controller comes from, it will go through the same steps looking for its view in the same order, as I explain in my book:

http://www.apeth.com/iOSBook/ch19.html#_view_controller_and_view_creation

and in this webcast:

http://www.youtube.com/watch?v=zIufcKpDIRo



来源:https://stackoverflow.com/questions/13199839/load-custom-uiview-with-xib-from-a-view-controllers-view-using-ib

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