iOS SDK:通过代码将button移动到屏幕中央

我想通过代码将一个button移动到屏幕的中心。 我看到的地方只是几行代码,却找不到它们。

这应该做到这一点:

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); 

这将button置于其超级视图中:

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

这里是更简单的方法:

 yourButton.center = self.view.center; 

公鸡117和DavidNg的答案似乎都是正确的。 只是为你添加一个“选项”,如果你想这样做animation,你应该这样做:

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

有一些方法可以不用编写任何代码。 如果您想要尝试使用界面设置将button置于屏幕中央,则可以查看我的剪辑 。

 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);