bringSubviewToFront problem?

30,195

Solution 1

The -[UIView bringSubviewToFront:] method only works for direct children, not grandchildren. Remember that the view hierarchy is a tree, and normally a view only knows about its "parent" (or superview) and its direct "children" (or subviews). You would need to do something like this:

// First, get the view embedding the grandchildview to front.
[self bringSubviewToFront:[grandchildview superview]];
// Now, inside that container view, get the "grandchildview" to front. 
[[grandchildview superview] bringSubviewToFront:grandchildview];

Solution 2

my contribution with the swift version from the checked solution

self.bringSubviewToFront(self.grandchildview.superview!)
self.grandchildview.superview!.bringSubviewToFront(self.grandchildview)
Share:
30,195
senthilM
Author by

senthilM

Updated on February 16, 2020

Comments

  • senthilM
    senthilM about 4 years

    HI, I have Parentview-->Multiple childviews. when i use [self bringSubviewToFront:childview] in parentview, it works fine.but after adding grandchildview to childview,when i use [self bringSubviewToFront: grandchildview] in parentview, it did not work?any help please?

  • Pizzaiola Gorgonzola
    Pizzaiola Gorgonzola over 10 years
    doing this recursively would be even better
  • DarkDust
    DarkDust over 10 years
    @PizzaiolaGorgonzola For arbitrary nesting levels, yes, a recursive method would be the way to go. For this simple case it would be overkill, though.
  • Supertecnoboff
    Supertecnoboff almost 9 years
    Thank you, I had been struggling with this issue for a while.
  • Jack Solomon
    Jack Solomon over 8 years
    Fantastic code - really clean and works! Thanks so much :)