84

In interface builder, there are layout options to send to back or send to front any elements such as UIButton, UIImage, UILabel etc...

Now, I would like to do the same at runtime, programmatically.

Is there an easy way to do that?

I do not want to create different views, just update the z-axis.

bneely
  • 9,083
  • 4
  • 38
  • 46
Yohann T.
  • 1,915
  • 2
  • 23
  • 28

2 Answers2

192

There are a number of methods of UIView that allow you to modify the view hierarchy.

Since your views are already inserted into your superview, you could easily call bringSubviewToFront: once for each view in whatever order you like.

Nikhil Manapure
  • 3,748
  • 2
  • 30
  • 55
Sebastian Celis
  • 12,185
  • 6
  • 36
  • 44
  • Are you saying that I can't directly send a UIButton to front/back? I have to create a view and add it to that view. Then use the methods above? If so, Is the controller class the place to create such a view? – Yohann T. Jun 28 '09 at 13:42
  • 11
    A UIButton is a subclass of UIView. Just call: [[myButton superview] bringSubviewToFront:myButton]; – Sebastian Celis Jun 28 '09 at 13:47
  • Just to clear a small doubt I had: if you insert a subview that's already in the view hierarchy, the OS will only move its position. So, inserting as long as the view exists will not cause any overhead. – olivaresF Jul 18 '11 at 21:45
  • "call `bringSubviewToFront:` once for each view in whatever order you like" thats a really trick. Good one. – Ans Aug 18 '15 at 20:39
43

You could use:

[self.view bringSubviewToFront:myButton];
Tom Walters
  • 15,366
  • 7
  • 57
  • 74
hanumanDev
  • 6,592
  • 11
  • 82
  • 146