How to create a custom UIView?

2019-06-12 07:56发布

问题:

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?

回答1:

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.



回答2:

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.



回答3:

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.