iPhone/iPad的UIButton标题标签文字无法显示

36

我创建了一个按钮网格。以下代码创建按钮并显示它们,但按钮上没有文本。是否存在我忽略的设置?(Obj-C 的回复没问题,我是双语者)

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);

你为什么在titleLabel中使用大写字母?应该是button.titleLabel而不是button.TitleLabel。 - Alex Zavatone
我在这里详细解释了 https://dev59.com/jWgu5IYBdhLWcg3wUlft#11417134 - Jesse Gumpo
7个回答

132

我认为你想要使用setTitle: forState:方法。

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

1
有趣的是,button.titleLable.text = @"Foo" 并不总是做正确的事情。你必须在 UIButton 上设置标题。 - David Potter
2
这太荒谬了,button.titleLabel.text 不起作用,但 [button setTile:.. forState:] 起作用,希望默认情况下为正常状态设置它或类似的东西。有什么评论吗? - Gmu
2
@Gmu 他们在苹果公司实施起来非常困难。 - LolaRun

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];

一个 UIButton 已经有了标签。通常情况下,像你展示的那样添加自己的标签是不必要的。@tobias-cohen 对这个问题和大多数情况都有正确的答案。 - Fabian

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

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

在这里,我创建了一个示例程序化按钮,并设置了其正常控制状态的标题。您可以使用自己的按钮对象设置标题字符串,此外,您还可以通过将UIControlStateNormal更改为其他所需状态来为另一些控制状态设置标题文本。


2

针对Swift开发人员-

button.setTitle("Your button Name", for: .normal)

2

在我的情况下 (Swift 4),代码如下:

btnLogin.setTitle("Welcome, " + var_name, for: [])

0
self.ButtonName.setTitle("Here Put Your variable model", for: .normal)

2
这不就是 @iDeveloper 三年前的回答 吗? - Jeremy Caney

-4
  self.Button_name.titleLabel.text = @"Your title name";

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接