Adding subviews on top of a programmatically-created UIView hierarchy

13,953

Just drag a generic UIView into a nib in Interface Builder and set its class to your custom subclass. You can still do everything you could with a plain old UIView, including drag-dropping subviews.

You won't be able to see what the custom subview actually looks like in Interface Builder; it will just be a gray rectangle. You could have (I think) done this in Xcode 3 with IB plugins, but, at least for the time being, Xcode 4 does not support such plugins.

EDIT:

To address the OP's follow-up, you need to manage z-ordering programmatically. Probably the easiest thing to do is to leave your code largely as-is, but instead of doing something like:

UIView *mySubview1 = ...;
UIView *mySubview2 = ...;
UIView *mysubview3 = ...;
[self addSubview:mySubview1];
[self addSubview:mySubview2];
[self addsubview:mySubview3];

(which, as you noted, may well layer the subviews on top of the user's subviews)

Do something like:

UIView *container = [[UIView alloc] initWithFrame:[self bounds]];
UIView *mySubview1 = ...;
UIView *mySubview2 = ...;
UIView *mysubview3 = ...;
[container addSubview:mySubview1];
[container addSubview:mySubview2];
[container addsubview:mySubview3];
[self addSubview:container];
[self sendSubviewToBack:container];
[container release];

You could alternatively use [self insertSubview:container atIndex:0] but I think that adding and moving to the back is a little clearer during a rapid skim of the code.

The end result is that you don't have to mess with the existing z-ordering of your subviews; by putting them in a single, easily-managed container, you can move the whole collection to wherever you would like in the subview hierarchy.

Share:
13,953
Tom
Author by

Tom

Updated on June 27, 2022

Comments

  • Tom
    Tom almost 2 years

    I have a UIView subclass that programmatically creates and adds a number of subviews. However, I want to give users of the class the ability to place new subviews over it (and its subviews) using addSubview and ideally from within Interface Builder as well.

    What is the best way to do this?

    Now, I suppose it would be acceptable to only add the views programmatically using addSubview, but I'm not sure how I would go about this either.

    NOTE: I've tried adding additional subviews using interface builder, but they're hidden once the custom UIView subclass I refered to above creates its other views programmatically, presumably since they're added last.

  • Tom
    Tom about 12 years
    This is what I tried initially. Unfortunately, since the custom class adds its other subviews programmatically, they appear over the views I added in IB.
  • Supertecnoboff
    Supertecnoboff over 8 years
    I think you should do [self.view addSubview:mySubview1];