Mateus
Mateus

Reputation: 2668

UIView and XIB connections.Displaying it?

How can i display an XIB/NIB file on a UIView?I've searched but i didn't found this.I want to display the xib interface on a main view,i have five xib files and i need to each one be displayed on a UIView!Some people talked about this code code but where i implement this:

NSArray *screens=[[NSBundle mainBundle] loadNibNamed:@"JaneiroClass" owner:self options:nil];          
        [self addSubview:[screens objectAtIndex:0]];

Upvotes: 0

Views: 738

Answers (2)

arclight
arclight

Reputation: 5310

I posted an article about loading custom views from a nib in my blog http://effectivemobility.blogspot.com/2011/05/using-custom-cells-in-your-uitableview.html

The key part is this method

+ (id)customViewForClass:(Class)customClass {
    NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:NSStringFromClass(customClass) owner:nil options:nil];
    for ( id currentObject in topLevelObjects ) {
        if ( [currentObject isKindOfClass:customClass] ) {
            return currentObject;
        }
    }

    return nil;
}

Upvotes: 1

bryanmac
bryanmac

Reputation: 39296

This will load a view from a XIB. UINib also caches so you can stamp them out quickly.

UINib *nib = [UINib nibWithNibName:@"TestView" bundle:nil];
UIView *myView = [[nib instantiateWithOwner:self options:nil] objectAtIndex:0]];

instantiateWithOwner returns an array of the top level objects in the XIB. In the case above, there was only one view (with other objects from the library on it) so we retrieved objectAtIndex:0.

Once you have the view, you can add it to other views. For example, you can call addSubView on another view passing this:

[someView addSubView:myView];

Upvotes: 2

Related Questions