6

I have a UIButton of type UIButtonRoundedRectType that I want to put in middle of the screen horizontally and vertically.

I've tried doing this by hardcoding numbers but this looks back when run on iPhone vs. iphone (retina). I would like to programmatically keep the button in the center by calculating the container's width.

So, I've tried this but it doesn't work.

container = view.frame.size
button = UIButton.buttonWithType(UIButtonTypeRoundedRect)
button.frame = [[container.width/2-button.frame.size.width/2,150], [280,50]]
Anthony
  • 33,838
  • 42
  • 169
  • 278
  • You can do this using Storyboards using layout constraints. That way you don't have to worry about hard coding anything. http://www.raywenderlich.com/5138/beginning-storyboards-in-ios-5-part-1 – Jordan Apr 11 '13 at 18:20
  • What doesn't work? What are you using for "view"? – Hot Licks Apr 11 '13 at 19:01
  • (Keep in mind that the above will only center within "view". If "view" is not centered then the button will be equally off-center.) – Hot Licks Apr 11 '13 at 19:03
  • the view is a UIViewController – Anthony Apr 11 '13 at 19:05

4 Answers4

10

Simple approach:

button.center = view.center;
Darius Miliauskas
  • 3,391
  • 4
  • 35
  • 53
6

How about:

button.center = [button.superview convertPoint:button.superview.center fromView:button.superview.superview];
Dejell
  • 13,947
  • 40
  • 146
  • 229
lnafziger
  • 25,760
  • 8
  • 60
  • 101
2

You weren't too far off. This works (I tried it):

container = view.frame.size
button = UIButton.buttonWithType(UIButtonTypeRoundedRect)
button_size = [ 280, 50 ]
left_margin = (container.width / 2) - (button_size[0] / 2)
top_margin = (container.height / 2) - (button_size[1] / 2)
button.frame = [[ left_margin, top_margin ], button_size ]
button.autoresizingMask = UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin
Jamon Holmgren
  • 23,738
  • 6
  • 59
  • 75
2

If you are using view in XIB you can use like that i have mentioned.

GO to XIB -> Click on View -> Click on Size Inspector -> Arrange (You can set position here).

enter image description here

Select all properties of Position of Container and Fill Container.

And if you creating view dynamically(not in XIB) then you can use according superview's bounds.

Nirav Jain
  • 5,088
  • 5
  • 40
  • 61