2012-07-17 67 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