How to put a button in middle of the UIView Horizontally and Vertically for any device?

Anthony picture Anthony · Apr 11, 2013 · Viewed 8.7k times · Source

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]]

Answer

Darius Miliauskas picture Darius Miliauskas · Jun 24, 2015

Simple approach:

button.center = view.center;