2009-04-09 75 views
8

什麼是中心在UIView標籤的最佳方式居中標籤?如果你做的事情如在一個UIView

UILabel *myLabel = [[UILabel alloc] initWithFrame:CGRectMake(view.frame.origin.x/2, view.frame.origin.y/2, 50.0, 50.0)]; 

然後,您將標籤的原點設置爲視圖的中心。最好的選擇是使用中心屬性將視圖的中心設置爲該點。所以我嘗試使用下面的代碼:

UIView *aView = [[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]; 
aView.backgroundColor = [UIColor darkGrayColor]; 
CGRect frame = aView.frame; 

UILabel *aLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 125.0f, 30.0f)]; 
[aLabel setCenter:CGPointMake(frame.origin.x/2, frame.origin.y/2)]; 

這產生了一個標籤,它幾乎超出了視圖左上角的範圍。

回答

18

你做錯了,主要就是採取起源值的一半,而不是尺寸的一半

但是,你並不需要,甚至計算出,在這種情況下 - 只是像做以下內容:


UIView *aView = [[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]; 
aView.backgroundColor = [UIColor darkGrayColor]; 

UILabel *aLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 125, 30)]; 
aLabel.center = aView.center; 

(注意,你並不需要這些座標強制花車 - 在這種情況下寫他們作爲整數似乎更可讀)。

此外,這是一個風格問題 - 但是,因爲你已經在使用屬性語法(aView.backgroundColor),你可能也使用它的中心物業太:-)

6

要定位任何水平居中在父母中的孩子,您可以像這樣計算其位置;

childX = (parentWidth - childWidth)/2 

(這也適用於身高)。

+0

感謝安德魯。你認爲哪些是學習這些幾何類型方程的最佳資源?簡單的幾何? – Coocoo4Cocoa 2009-04-10 00:20:17

+4

說實話,我不知道,像這樣的東西只是基本的數學 - 你有一個你想分佈在兩邊(/ 2)的一定數量的空間(parentWidth - childWidth)。 – 2009-04-10 00:31:09