2012-09-12 25 views

回答

19

可以設置按鈕的中心將其置於相應

yourButton.center = CGPointMake(0.0, 0.0);// for topleft 

yourButton.center = CGPointMake(160.0, 240.0);// for center 

yourButton.center = CGPointMake(320.0, 480.0);// for bottomright 

希望這會有幫助

+3

但是,這並不能補償按鈕的大小。例如,在第一行中,您的按鈕將部分隱藏。 – woz

+2

其實這傢伙想要對齊按鈕(頂部,底部或中間),而不是設置框架,因此我給出了我的答案 –

+0

320和480是否也是iPhone 5或5S的有效指標? –

3

您應該設置它的框架。

喜歡的東西

UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(320, 120, 35, 10)]; 

button.frame = CGRectMake(320, 120, 35, 10); 

請注意,第一對值分別是視圖和第二的寬度和高度(位置在X和Y)值的一對是按鈕本身的寬度和高度。

所以,如果你想在頂部的按鈕,你應該輸入

button.frame = CGRectMake(0, 0, 35, 10); 

中東

button.frame = CGRectMake(160, 240, 35, 10); 

底部

button.frame = CGRectMake(320, 480, 35, 10); 
+0

哦,好的,非常感謝!你們好棒! – iHackerMe

+0

我必須等待8分鐘來接受這個答案:P StackOverFlow不會讓我接受答案如此之快:)不過,我會肯定接受它後,長8分鐘等待:) – iHackerMe

+0

沒有問題,重要的是,你有怎麼樣去做吧! – Phillip

5

設置子視圖的位置的唯一途徑是手動的。您可以設置框架,這樣,例如:

enter image description here

或改變原產地,像這樣的,例如:

view.frame.origin.x = INT_VALUE;

獲得某種比對的唯一途徑是與self.view.frame做數學。如果你想與屏幕的中間水平對齊對象,請使用:如果要對齊東西頂用的44個像素的邊距

view.frame.origin.x = self.view.frame.size.width/2

,使用此:

view.frame.origin.y = self.view.frame.origin.y = (view.frame.size.height/2) + 44;

等等

+0

我喜歡你回答的絕對性。 「唯一的方法」xD –

53

你必須設置UIButton構架你的自我。

平鋪對齊

float X_Co = (self.view.frame.size.width - yourButtonWidth)/2; 
[button setFrame:CGRectMake(X_Co, yourYposition, yourButtonWidth, yourButtonheight)]; 

垂直對齊

float Y_Co = (self.view.frame.size.height - yourButtonheight)/2; 
[button setFrame:CGRectMake(yourXposition, Y_Co, yourButtonWidth, yourButtonheight)]; 

左上

[button setFrame:CGRectMake(0.0, 0.0, yourButtonWidth, yourButtonheight)]; 

右上方

float X_Co = self.view.frame.size.width - yourButtonWidth; 
[button setFrame:CGRectMake(X_Co, 0.0, yourButtonWidth, yourButtonheight)]; 

左下角

float Y_Co = self.view.frame.size.height - yourButtonheight; 
[button setFrame:CGRectMake(0.0, Y_Co, yourButtonWidth, yourButtonheight)]; 

右下角

float X_Co = self.view.frame.size.width - yourButtonWidth; 
float Y_Co = self.view.frame.size.height - yourButtonheight; 
[button setFrame:CGRectMake(X_Co, Y_Co, yourButtonWidth, yourButtonheight)]; 

中心self.view中

button.center = self.view.center; 
OR 
float X_Co = (self.view.frame.size.width - yourButtonWidth)/2; 
float Y_Co = (self.view.frame.size.height - yourButtonheight)/2; 
[button setFrame:CGRectMake(X_Co, Y_Co, yourButtonWidth, yourButtonheight)]; 
+4

雖然這個答案是正確的,但是當你將一個框架居中放置時,或者寬度是一個不均勻的像15像素的值時,你可能會遇到圖形問題。框架可能會以半個像素開始,使視圖模糊。爲了解決這個問題,一個解決方案可能是在設置中心之後使用'button.frame = CGRectIntegral(button.frame);'來糾正幀。 –

+0

但X_Co和Y_Co是浮點值。 – TheTiger

+0

謝謝大家的回答!我希望我能接受他們所有的人!我是一個新手,不知道我需要在什麼地方放置什麼數字或價值。有沒有任何指導理解了解屏幕高度寬度等值? – iHackerMe

相關問題