UIButton titleLabel不显示

Pet*_*ter 36 iphone uibutton ios ios6

我见过一堆类似的问题,但没有人得到我想要的答案.当我使用此代码制作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];
Run Code Online (Sandbox Code Playgroud)

此代码显示按钮,但不显示titleView,它的标题.为什么会这样?我正在为iOS 6及更高版本开发.

注1:我不是在寻找这样的选项:

[button setTitle:@"Title" forState:UIControlStateNormal];
Run Code Online (Sandbox Code Playgroud)

因为我必须使用titleLabel来设置它的font和fontSize.

注意2:我无法创建UILabel并将其添加为按钮的子视图.由于按钮后来是动画.

mdz*_*iec 81

更新按钮标题时总是需要指定ControlState!UIButtons有四个可能的值:

UIControlStateNormal
UIControlStateHighlighted
UIControlStateDisabled
UIControlStateSelected
Run Code Online (Sandbox Code Playgroud)

例如:

[button setTitle:@"Title" forState:UIControlStateNormal];
Run Code Online (Sandbox Code Playgroud)

然后你可以为titleLabel设置自定义设置:

[button.titleLabel setFont:[UIFont fontWithName:@"Zapfino" size:20.0]];
[button.titleLabel setTextColor:[UIColor blueColor]];
Run Code Online (Sandbox Code Playgroud)

  • 您应该使用`setTitleColor:forState`来设置标题的颜色(而不是在`titleLabel`上调用`setTextColor`). (3认同)

and*_*tis 9

[button setTitle:@"Title" forState:UIControlStateNormal];
Run Code Online (Sandbox Code Playgroud)

是设置标题字符串的正确方法.

titleLabel用于设置字体和颜色.