Laurent Crivello
Laurent Crivello

Reputation: 3931

Add a subview from within and below another subview

In an iOS app, I am adding a subview to my main view with:

[self.view addSubview:firstUIImageSubview];

However in the subview class firstUIImageSubview, I am creating and adding another subView (secondUIImageSubview) that I would like to put below the first subview with:

[self insertSubview:secondUIImageSubview belowSubview:self];

My problem is that the second subview is displayed above the first subview when I want to have it below. How is it possible to achieve that ? Thanks.

Upvotes: 0

Views: 844

Answers (2)

Literphor
Literphor

Reputation: 498

When you use insertSubview:belowSubview: it places the subview in regards to other subviews that particular object manages.

[self insertSubview:secondUIImageSubview belowSubview:self];

Doesn't make much sense. Although self is a UIView (or a subclass) it still should never manage itself as a subview. Therefore

[self insertSubview:secondUIImageSubview belowSubview:firstUIImageSubview];

is probably what you want. But remember this will only place the secondUIImageSubview below firstUIImageSubview in terms of its Z-Index (it's depth on the screen). If you want it to be physically placed below firstUIImageSubview (IE it's XY coordinate) then you need to set it's position using subview's frame or setting its origin instead (by manipulating it's center or anchor points for instance).

Upvotes: 0

Bay Phillips
Bay Phillips

Reputation: 2045

This should do the trick.

[self.superview insertSubview:secondUIImageSubview atIndex:0];

Upvotes: 1

Related Questions