views:

202

answers:

3

I've created a UIView subclass and corresponding xib file where I've laid out some UILabels and UIImageViews. I want to then put multiple copies of this custom UIView into a UIViewController.

When I do that they appear blank in interface builder and don't appear when the app loads. What methods do I need to implement on the UIView subclass to make this work?

A: 

This is similar to using a nib file to create table view cells. Here is a page that discusses how to do that.

You'll need to put an outlet in your UIViewController subclass for the custom view, and set the UIViewController subclass as the "File's Owner" in your custom view nib (.xib) file. Then connect the outlet you created to the top-level view object (again in your custom view nib file).

Then each time you want to instantiate your custom view in your view controller code, call:

[[NSBundle mainBundle] loadNibNamed:<custom view nib name> owner:self options:nil];

The outlet you added will then be set to point to a new instance of your custom view.

The only downside to this approach is that you will have to lay out the instances of your custom view in your view controller programatically rather than graphically in interface builder.

Another approach would create the put labels and images programatically in your UIView subclass, and then you can add it to interface builder like you would any other UIView subclass.

Frank Schmitt
What method do I need to implement to add the UI elements to the custom UIView? Is it`- (id)initWithCoder:(NSCoder *)decoder` ?
xmr
See my new answer, you can leave out the outlet fiddling and use the array returned by loadNibNamed.
mvds
@xmr: I think just plain old `init`.
Frank Schmitt
A: 

See also Adding Custom Objects to the Library.

Once you have your subview configured in Interface Builder, you can create a new group (use the cog button at the bottom of the library window) and drag your subclass object (containing your images and labels) from the list view (i.e. not the layout view) back to the library window.

You can then graphically add multiple instances of your view subclass to any interface builder view or window like you would with the built-in objects in the library.

Frank Schmitt
+2  A: 

The easiest method by far is to create a nib with File's Owner set to NSObject, containing one view containing your layout element.

Then

NSArray *arr = [[NSBundle mainBundle] loadNibNamed:@"MyView" owner:nil options:nil];
UIView *fv = [[arr objectAtIndex:0] retain];

// now you have the view, do something with it:
fv.center = CGPointMake(100,100);
[self.view addSubview:fv];

No need to do anything with the file's owner; it is even set to nil here.

mvds