2013-05-20 48 views
28

我看到了一堆類似的問題,但沒有人得到我正在尋找的答案。當我使用這段代碼創建一個UIButton並將其設置爲titleLabel時,會出現UIButton,但titleLabel不會出現。UIButton titleLabel沒有顯示

UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 50, 50)]; 
[button setBackgroundImage:[UIImage imageNamed:@"button.png"] forState:UIControlStateNormal]; 
button.titleLabel.text = @"Title"; 
button.titleLabel.font = [UIFont fontWithName:@"System-Bold" size:25.0f]; 
[self.view addSubview:button]; 

此代碼顯示按鈕,但不是titleView,它的標題。爲什麼會這樣?我正在開發iOS 6和更高版本。

注1:我不是在尋找這樣一個選項:

[button setTitle:@"Title" forState:UIControlStateNormal]; 

因爲我必須使用titleLabel來設置它的字體和中文字體。

注意2:我無法創建UILabel並將其作爲子按鈕添加。由於該按鈕後來有動畫效果。

回答

66

更新按鈕標題時,您總是需要指定ControlState! 有用於UIButtons四個可能的值:

UIControlStateNormal 
UIControlStateHighlighted 
UIControlStateDisabled 
UIControlStateSelected 

因此,例如:

[button setTitle:@"Title" forState:UIControlStateNormal]; 

,然後你可以設置自定義設置titleLabel:

[button.titleLabel setFont:[UIFont fontWithName:@"Zapfino" size:20.0]]; 
[button.titleLabel setTextColor:[UIColor blueColor]]; 
+3

您應該使用'setTitleColor:forState'來設置顏色(而不是在'titleLabel'上調用'setTextColor')。 – hverlind

8
[button setTitle:@"Title" forState:UIControlStateNormal]; 

是設置標題字符串的正確方法。

titleLabel用於設置字體和顏色。

+0

注1:我不是在尋找這個答案。我不能用這個字體! – Peter

+1

titleLabel用於設置由setTitle設置的字符串的字體和顏色:forState: –

+0

非常感謝,我一直在尋找這麼久:D –

2

嘗試使用...

[button setNeedsLayout]; 
[button layoutIfNeeded]; 

它將強制按鈕更新佈局。