如何在任何设备的水平和垂直UIView中间放置一个按钮?

时间:2013-04-11 18:17:24

标签: iphone objective-c rubymotion

我有一个类型为UIButtonRoundedRectType的UIButton,我希望水平和垂直放置在屏幕中间。

我已经尝试通过硬编码来做到这一点,但这在iPhone和iphone(视网膜)上运行时回顾过去。我想通过计算容器的宽度以编程方式将按钮保持在中心位置。

所以,我试过这个,但它不起作用。

container = view.frame.size
button = UIButton.buttonWithType(UIButtonTypeRoundedRect)
button.frame = [[container.width/2-button.frame.size.width/2,150], [280,50]]

4 个答案:

答案 0 :(得分:8)

简单方法:

button.center = view.center;

答案 1 :(得分:6)

怎么样:

button.center = [button.superview convertPoint:button.superview.center fromView:button.superview.superview];

答案 2 :(得分:2)

你离我太远了。这有效(我试过了):

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

答案 3 :(得分:2)

如果你在XIB中使用视图,你可以像我提到的一样使用。

转到XIB - >点击查看 - >点击Size Inspector - >安排(你可以在这里设置位置)。

enter image description here

选择Position of ContainerFill Container的所有属性。

如果你动态创建视图(不是在XIB中),那么你可以使用超级视图的界限。