Jim
Jim

Reputation: 9234

iPhone: How to load a View using a nib file created with IB

I found similar question here: How to load a UIView using a nib file created with Interface Builder. But my problem is a little different. I need to load my custom view into 2 or 3 different UIViewControllers. Here is there answer that I like https://stackoverflow.com/a/4055353/602011 But I cannot set for myViewXib FileOwner three UIViewCOntrollers together. How to be?

Upvotes: 0

Views: 121

Answers (2)

Kenny Lövrin
Kenny Lövrin

Reputation: 801

If you want to have one single xib file as the xib for several view controllers, so that basically all controllers have the same outlets, but different internal logic, I'd say you can create a base class with the outlets, set IB to use that class in the xib, then inherit your other controllers from that one.

That way you can load you generic view and have it connected with your more specific controllers. But that will only work if it is exactly the same xib for all the controllers.

This is based on that I imagine you want to do something like this:

AViewController *c1 = [[AViewController alloc] initWithNibName:@"MyXib" bundle:nil];
BViewController *c2 = [[BViewController alloc] initWithNibName:@"MyXib" bundle:nil];

Upvotes: 0

wrren
wrren

Reputation: 1311

In IB, you can set the FileOwner class type to UIViewController, then load the NIB using NSBundle's loadNibNamed:owner:options: method and iterate through the objects returned in order to modify or reference any child UIViews in the NIB.

NSArray* topLevelObjects = [ [ NSBundle mainBundle ] loadNibNamed:"bla" 
                                                     owner:self 
                                                     options:nil ] ];

for( id object in topLevelObjects )
{
    if( [ object isKindOfClass:[ UILabel class ] ] )
    {
         UILabel* label = ( UILabel* ) object;
         label.text = @"This is My Label Now!";
    }
}

Upvotes: 2

Related Questions