开发者

Load a UIView from a NIB as a subview of another UIView loaded also from a NIB

开发者 https://www.devze.com 2023-02-20 07:57 出处:网络
The idea basically is: Inside of myViewController NIB I have a UIView as a subview, with connections to an IBOutlet on MyViewController class. I want to load the UIView subview from a NIB also. The su

The idea basically is:

Inside of myViewController NIB I have a UIView as a subview, with connections to an IBOutlet on MyViewController class. I want to load the UIView subview from a NIB also. The subView also has a class associated with it. But the subview is not showing. Here is what I do

on MyViewController.h

@interface MyViewController : UIViewController {
    IBOutlet SubView *subView;     // this outlet is connected to an empty UIView on IB
}
@end

on MyViewController.m

-(id)init {
    if ((self = [super init])) {
        // load the main view 
        [[NSBundle mainBundle] loadNibNamed:@"myViewController" owner:self options:nil];
        // load the sub view from another NIB
        self.subView = [[[NSBundle mainBundle] loadNibName开发者_如何转开发d:@"subView" owner:self options:nil] objectAtIndex:0];
    }
}

the SubView.h is defined as:

@interface SubView : UIView {
}
@end

What am I doing wrong?


What you need to do is set your file owner to be a UIViewController, hook up your view to the view property of the file owner, save your nib. In your code, load your nib like this:

UIViewController* c = [[UIViewController alloc] initWithNibName:@"Foo" bundle:nil];
SubView* subView = [c view];

Should be off to the races.

One final note, is that the type of subView should be the same as whatever is defined as the class name in interface builder. If it's a SubView there, then it's safe to declare it as a SubView* in code.


GianPac - shameless self-promotion, but I did a blog post about this about a month ago. Feel free to ignore the drop-shadow related code.

http://nathanhjones.com/2011/02/20/creating-reusable-uiviews-with-a-drop-shadow-tutorial/

Also, I (thanks to advice from several people) avoid ever having more than one view controller on my 'view'. The method I outline above allows you to accomplish this and still use IB to do the layout/outlets.

0

精彩评论

暂无评论...
验证码 换一张
取 消