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?
Asked
Active
Viewed 3.1k times
2 Answers
64
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];

DarkDust
- 90,870
- 19
- 190
- 224
-
doing this recursively would be even better – Pizzaiola Gorgonzola Aug 28 '13 at 20:43
-
1@PizzaiolaGorgonzola For arbitrary nesting levels, yes, a recursive method would be the way to go. For this simple case it would be overkill, though. – DarkDust Aug 29 '13 at 11:02
-
Thank you, I had been struggling with this issue for a while. – Supertecnoboff Jul 12 '15 at 15:35
-
Fantastic code - really clean and works! Thanks so much :) – Jack Solomon Sep 24 '15 at 12:33
1
my contribution with the swift version from the checked solution
self.bringSubviewToFront(self.grandchildview.superview!)
self.grandchildview.superview!.bringSubviewToFront(self.grandchildview)

Kevin ABRIOUX
- 16,507
- 12
- 93
- 99