2009-06-26 63 views
12

在UIViewController的viewDidLoad方法中,我這樣做:爲什麼不顯示UIButton標題?

UIButton *b = [[UIButton buttonWithType:UIButtonTypeRoundedRect] 
             initWithFrame:CGRectMake(0, 0, 100, 100)]; 

[b setTitle:@"Testing" forState:UIControlStateNormal]; 
[b setTitleColor: [UIColor blackColor] forState: UIControlStateNormal]; 
[self.view addSubview:b];      // EDIT: should be 'b' 
NSLog(@"button title: %@", [b titleLabel].text); 

的按鈕顯示,但標題不會。 NSLog行將「測試」打印到控制檯。任何建議我做錯了什麼?

+0

兩個想法:*如果你讓你的按鈕更大? *你在做viewDidLoad中的其他任何可能影響按鈕的東西嗎? – JonathonW 2009-06-26 04:48:16

+0

請參閱diederikh的解決方案,因爲它描述了上面使用的double初始化程序中的錯誤以及它的修復方法,即在便捷初始化程序[...按鈕與類型...]完成後單獨分配幀。 OP自己的解決方案的其餘部分是正確的,保持不變。 – eGanges 2015-06-21 03:46:40

回答

38

我不能告訴你爲什麼它不工作,但我有一個解決方案:

UIButton *b = [UIButton buttonWithType:UIButtonTypeRoundedRect] ;   
b. frame = CGRectMake(0, 0, 100, 100); 

[b setTitle:@"Testing" forState:UIControlStateNormal]; 
[b setTitleColor: [UIColor blackColor] forState: UIControlStateNormal]; 
[self addSubview:b]; 

單獨創建一個從按鈕的配置和初始化框架。

4

而是執行此操作:

UIButton *b = [UIButton buttonWithType:UIButtonTypeRoundedRect]; 
b.frame = CGRectMake(0, 0, 100, 100); 
[b setTitle:@"Testing" forState:UIControlStateNormal]; 
[b setTitleColor: [UIColor blackColor] forState: UIControlStateNormal]; 
[self.view addSubview:b]; 
22

問題在於

UIButton *b = [[UIButton buttonWithType:UIButtonTypeRoundedRect] 
             initWithFrame:CGRectMake(0, 0, 100, 100)]; 

buttonWithType返回一個自動釋放初始化的對象。你不能再發送一個initWithFrame,因爲一個對象只能被初始化一次。

單獨設置它的框架:

b.frame = CGRectMake(0, 0, 100, 100); 
0

的事情是你必須去[[UIButton alloc] initWithFrame:][UIButton buttonWithType:],你不應該都使用起來。

0

你可以做到以下幾點:

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

b=[UIButton buttonWithType:UIButtonTypeRoundedRect];

[b setTitle:@"Button Title Here" forState:UIControlStateNormal]; 
[b setTitleColor:[UIColor blackColor] forState: UIControlStateNormal]; 
[self.view addSubview:b]; 
0

我有同樣的問題,它結束了,我是設置圖像,而不是和backgroundImage的事實。這一切都工作得很好,當我這樣做:

[button setBackgroundImage:image forState:UIControlStateNormal];