2012-07-17 70 views

回答

15

这应做到:

yourButton.frame = CGRectMake(self.view.frame.size.width/2 - yourButton.frame.size.width/2, self.view.frame.size.height/2 - yourButton.frame.size.height/2, yourButton.frame.size.width, yourButton.frame.size.height); 
+0

感谢完美的工作太 – DavidNg 2012-07-17 18:44:14

+0

这似乎运作良好的画像,但没有景观,我是不是做错了什么? – Rob85 2015-11-24 19:31:19

23

这在它的父居中按钮:

CGRect bounds = button.superview.bounds; 
button.center = CGPointMake(CGRectGetMidX(bounds), CGRectGetMidY(bounds)); 
+1

这不等于'[button setCenter:superview.center]'? – 2013-11-11 20:52:52

+0

不,中心是在超视图的坐标系中测量的,所以将按钮的“中心”设置到超视图的超视图中间。 – 2013-11-11 20:59:47

1

两个rooster117和DavidNg答案似乎是正确的。只是多了一个“选择”添加到你,如果你想这样做的动画,你应该做的:

NSTimeInterval seconds = 1.0; 
[UIView animateWithDuration:seconds animations:^{ 
    //here you should write any reframing/repositioning code 
}]; 
+0

嗨布鲁诺,如果我想要一个按钮来限制特定颜色,例如红色,那该怎么办? – DavidNg 2012-07-17 18:45:29

+0

只需将颜色更改代码放入动画块中即可。例如: NSTimeInterval seconds = 1.0; [UIView animateWithDuration:秒动画:^ {[myButton setBackgroundColor:[UIColor redColor]]; }]; – 2012-07-23 19:08:23

0

有一些方法来做到这一点无需编写任何代码。 如果您想要尝试使用界面设置将按钮置于屏幕中央,则可以使用view my clip

0
bntTimeEtrySave.Frame =new CoreGraphics.CGRect (
    this.View.Center.X-((bntTimeEtrySave.Bounds.Size.Width)/2), 
    bntTimeEtrySave.Frame.Y,bntTimeEtrySave.Bounds.Size.Width, 
    bntTimeEtrySave.Bounds.Size.Height); 
+1

欢迎来到StackOverflow!仅限代码答案[不鼓励](http://meta.stackexchange.com/a/148274/230241);请编辑您的答案,至少包括一些解释其原因。 – ravron 2015-04-06 13:42:07

2

这里有更简单的办法:

yourButton.center = self.view.center; 
+0

这是正确的答案!如果需要,请在x或y中使用center.x或center.y作为具体细节! – 2016-01-01 15:37:06

+0

你如何使这种支持方向发生变化? :( – 2016-01-01 15:39:25