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?
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
No need to do anything with the file's owner; it is even set to nil here.
Edit: Unfortunately in Xcode 4.0, this capability was removed.
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.
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 theUIViewController
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:
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 otherUIView
subclass.