How to place a button in the middle of a UIView horizontally and vertically for any device?

I have a UIButton of type UIButtonRoundedRectType, which I want to place horizontally and vertically in the middle of the screen.

I tried to do this by the hard drive numbers, but it looks back when working on an iPhone against an iphone (retina). I would like to programmatically hold the button in the center while calculating the width of the container.

So, I tried this, but it does not work.

container = view.frame.size
button = UIButton.buttonWithType(UIButtonTypeRoundedRect)
button.frame = [[container.width/2-button.frame.size.width/2,150], [280,50]]
+5
source share
4 answers

Simple approach:

button.center = view.center;
+8
source

What about:

button.center = [button.superview convertPoint:button.superview.center fromView:button.superview.superview];
+6
source

. ( ):

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
+1

XIB, , .

Go to XIB → Click on View → Click on Size Inspector → Arrange (Here you can set the position).

enter image description here

Select all properties Position of Containerand Fill Container.

And if you create a view dynamically (not in the XIB), you can use the appropriate viewing restrictions.

+1
source

All Articles