2010-03-07 64 views
34

我創建了一個按鈕的網格。以下代碼創建按鈕並顯示它們,但按鈕上沒有文本。有沒有我失蹤的設置? (OBJ - C的答覆都很好,我很雙語)iPhone/iPad的UIButton TitleLabel文本沒有出現

RectangleF frame = new RectangleF (X + 3, Y + 3, cellWidth - 2, cellHeight - 2); 
UIButton button = new UIButton (frame); 
button.TitleLabel.Text = "Baha'i"; 
button.TitleLabel.Font = UIFont.FromName ("Helvetica-Bold", 15); 
button.TitleLabel.TextColor = UIColor.Black; 
button.TitleLabel.Frame = frame; 
button.BackgroundColor = UIColor.FromWhiteAlpha(.5f,.5f); 
this.AddSubview (button); 
+0

你爲什麼使用大寫字母titleLabel?它是button.titleLabel,而不是按鈕。** T ** itleLabel。 – 2015-11-04 13:05:23

+0

我已經詳細解釋了這裏http://stackoverflow.com/a/11417134/1149906 – 2016-06-07 06:37:15

回答

128

我想你想setTitle: forState:

[button setTitle:@"Baha'i" forState:UIControlStateNormal] 
+1

有趣的是,button.titleLable.text = @「Foo」並不總是做正確的事情。你必須在UIButton本身設置標題。 – 2012-02-20 23:27:02

+2

這是荒謬的button.titleLabel.text沒有任何工作,但[按鈕setTile:.. forState:]工作希望它默認設置爲正常狀態或東西。註釋? – Gmu 2013-09-20 04:07:15

+2

@Gmu他們發現在蘋果公司實施起來非常困難 – LolaRun 2014-09-03 22:18:47

6

一個UIButton從UIView的繼承,所以另一種方式來添加文本和圖像,是添加子視圖。例如:

// My Image 
UIImage *buttonImage = [UIImage imageNamed:@"myImage.png"]; 
UIImageView *buttonImageView = [[[UIImageView alloc] 
    initWithFrame:CGRectMake(0, 0, 
    buttonImage.size.width,buttonImage.size.height)] autorelease]; 
[buttonImageView setImage:buttonImage]; 

// My Label 
UILabel* titleLabel = [[[UILabel alloc] 
    initWithFrame:CGRectMake(0, 0, 
    buttonImage.size.width, buttonImage.size.height)] autorelease]; 
titleLabel.text = @"My Text"; 
titleLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size: 11.0]; 
titleLabel.textColor = [UIColor blackColor]; 
titleLabel.backgroundColor = [UIColor clearColor]; 
titleLabel.textAlignment = UITextAlignmentCenter; 

// Create Button with Image and Label 
UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom]; 
[button addSubview:buttonImageView]; 
[button addSubview:titleLabel]; 
+0

「UIButton」已經有一個標籤。通常不需要添加你自己的東西。 @ tobias-cohen對這個問題和大多數情況都有正確的答案。 – Fabian 2013-05-13 21:08:49

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

[selectCountryBtn setTitle:@"My Title" forState:UIControlStateNormal]; 

在這裏,我有創建示例程序按鈕,然後設置標題爲它的正常控制的狀態,您可以使用您自己的按鈕對象設置標題字符串,此外,您還可以設置另一個控件的標題文本通過將UIControlStateNormal更改爲另一個所需的狀態。

0

爲SWIFT Developers-

button.setTitle("Your button Name", forState: .Normal)