Search code examples
iosuiviewlayersubviews

Reordering UIView subviews


In my app I am trying bring a subview to front, then put it back to its original layer position later. The code should be pretty simple:

To bring the subview to front (inside my custom UIView class):

[self.superview bringSubviewToFront:self];

Easy. I store the original z position in an instance variable called, you guessed it, zPosition. So, the line before -bringSubviewToFront: is:

zPosition = [self.superview.subviews indexOfObject:self];

So, all of the code I use to bring my subview to front is:

zPosition = [self.superview.subviews indexOfObject:self];
[self.superview bringSubviewToFront:self];

This works as it should. The problem is when I try to put the subview back where it was. I'm simply doing this:

[self.superview exchangeSubviewAtIndex:zPosition withSubviewAtIndex:
    [self.superview.subviews indexOfObject:self]];

Using this code, if I have two subviews, this is what happens:

Let's say I have view A and view B. View A is above view B. I tap view B, it comes to the front. I tap view B again (it should go back to where it was), and nothing happens, so it's now on view A. If I now tap view A, it comes to the front, but when I tap it again (so it should go back to its original z position: below view B), all of its sibling views disappear!

Does anyone see what could be causing this problem?


Solution

  • exchangeSubviewAtIndex may well put the view back in the right place, but it will also swap another view on top, which wont be what you started with. You might need to do something like this instead of exchangeSubviewAtIndex :

    [self retain];
    UIView *superview = self.superview;
    [self removeFromSuperview];
    [superview insertSubview:self atIndex:zPosition];
    [self release];