36

I have seen a bunch of similar questions, but noone got the answer I am looking for. When I use this code to make a UIButton and set it's titleLabel, the UIButton appear, but the titleLabel won't appear.

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

This code displays the button, but not the titleView, it's title. Why can that be? I am developing for iOS 6 and higher.

NOTE 1: I am not looking for an option like this:

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

Because I have to use the titleLabel to set it's font and fontSize.

NOTE 2: I can't create a UILabel and add it as a subView of the button. Since the button is later animating.

4

6 に答える 6

83

ボタンのタイトルを更新するときは、常に ControlState を指定する必要があります。UIButtons には 4 つの可能な値があります。

UIControlStateNormal
UIControlStateHighlighted
UIControlStateDisabled
UIControlStateSelected

たとえば、次のようになります。

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

そして、titleLabel のカスタム設定を設定できます。

[button.titleLabel setFont:[UIFont fontWithName:@"Zapfino" size:20.0]];
[button.titleLabel setTextColor:[UIColor blueColor]];
于 2013-05-20T19:46:06.980 に答える
10
[button setTitle:@"Title" forState:UIControlStateNormal];

タイトル文字列を設定する正しい方法です。

titleLabel は、フォントと色を設定するために使用されます。

于 2013-05-20T19:34:43.330 に答える
3

使ってみて...

[button setNeedsLayout];
[button layoutIfNeeded];

ボタンにレイアウトの更新を強制します。

于 2014-10-14T14:14:04.803 に答える