2011-11-28 77 views
0

我試圖以編程方式創建按鈕並使其可見。這就是我所做的:無法創建UIButton

UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(100, 100, 100, 100)]; 
button = [UIButton buttonWithType:UIButtonTypeRoundedRect]; 
[self.view bringSubviewToFront:button]; 

沒什麼。它不可見。我究竟做錯了什麼?

回答

1

當你這樣做:

UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(100, 100, 100, 100)]; 

你創建大小爲100×100的按鈕,但尚未將其添加到視圖。然後,當你這樣做:

button = [UIButton buttonWithType:UIButtonTypeRoundedRect]; 

你正在做一個新按鈕,尺寸爲0x0,仍然沒有將它添加到視圖。第一個按鈕將永遠留在內存中。然後,當你這樣做:

[self.view bringSubviewToFront:button]; 

你告訴視圖帶來了新的按鈕,在視圖的前 - 但它尚未在屏幕上。你真正想做的事是這樣的:

UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect]; 
button.frame = CGRectMake(100, 100, 100, 100); 
[self.view addSubview:button]; 

,創建一個按鈕,設置其框架,然後將其添加到您的視圖。

0

您應該使用[self.view addSubview:button];而不是 - 它會有所幫助。此外,你分配*button兩次,所以第一個(與框架的一個)將被忽略。

1

您需要將按鈕添加到視圖。

[self.view addSubview:button]; 
0

你的第二個行之後添加

[self.view addSubview: button]; 

此外,你正在創建2個按鈕 - 你的前兩行創建一個按鈕。選一個!

0

你永遠不會將按鈕附加到主視圖。我的猜測是你很困惑bringSubviewToFront:addSubview

[self.view addSubview:button]; 
0

有幾件事情是錯誤的。首先,你創建兩個按鈕。您正在第一行創建一個,然後在第二行創建另一個。此外,您還需要將按鈕添加到您的視圖:

[self.view addSubview:button]; 
0

添加使用

[self.view addsubview:button]; 
按鈕