9

我正在尝试动态更新 s 的IBOutletCollection标题UIButton。我希望标题设置为

  • 选择时的字母“S”和
  • 禁用和选择时的文本“D|S”。

它不起作用,所以我打印了titleForState:s ,看起来标题设置不正确。我使用setTitle: forState:正确吗?

@property (strong, nonatomic) IBOutletCollection(UIButton) NSArray *buttons;
...
- (void)updateUI  // Calling this from IBAction
{
    for(UIButton *button in self.buttons) {
        [button setTitle:@"S" forState:UIControlStateSelected];
        [button setTitle:@"D|S" forState:UIControlStateSelected|UIControlStateDisabled];

        NSLog(@"%@ %@ %@ %@ %d %d",
              [button titleForState:UIControlStateSelected],
              [button titleForState:UIControlStateSelected],
              [button titleForState:UIControlStateNormal],
              [button titleForState:UIControlStateSelected|UIControlStateDisabled],
              button.selected,
              button.enabled);
    }
}

这是控制台输出:

2013-02-21 21:05:36.070 Buttons[37130:c07] D|S D|S   0 1
2013-02-21 21:05:36.072 Buttons[37130:c07] D|S D|S   0 1
2013-02-21 21:05:36.073 Buttons[37130:c07] D|S D|S   0 1
2013-02-21 21:05:36.073 Buttons[37130:c07] D|S D|S   0 1
2013-02-21 21:05:36.073 Buttons[37130:c07] D|S D|S   0 1
2013-02-21 21:05:36.074 Buttons[37130:c07] D|S D|S   0 1
2013-02-21 21:05:36.074 Buttons[37130:c07] D|S D|S   0 1
2013-02-21 21:05:36.074 Buttons[37130:c07] D|S D|S   0 1
2013-02-21 21:05:36.075 Buttons[37130:c07] D|S D|S   0 1
2013-02-21 21:05:36.075 Buttons[37130:c07] D|S D|S   0 1
2013-02-21 21:05:36.076 Buttons[37130:c07] D|S D|S   0 1
2013-02-21 21:05:36.076 Buttons[37130:c07] D|S D|S   0 1
4

3 回答 3

20

它不起作用,因为 IB 设置attributedTitle而不是title.

试试这个:

NSAttributedString *attributedTitle = [self.myButton attributedTitleForState:UIControlStateNormal];
NSMutableAttributedString *mas = [[NSMutableAttributedString alloc] initWithAttributedString:attributedTitle];
[mas.mutableString setString:@"New Text"];

[self.myButton setAttributedTitle:mas forState:UIControlStateNormal];

或者,或者:

[self.myButton setAttributedTitle:nil forState:UIControlStateNormal];
[self.myButton setTitle:@"New Text" forState:UIControlStateNormal];

(第二个选项不会保留您的格式。)

于 2013-11-26T20:03:42.793 回答
1

在尝试了很多不同的事情之后,我让它工作的唯一方法如下。但这是一个 C 风格的逻辑,会改变 UIButton 控件状态的选中和禁用含义。绝对是一个黑客:(

//        [cardButton setTitle:card.contents
//                    forState:UIControlStateSelected|UIControlStateDisabled];
if(cardButton.selected && !cardButton.enabled) {
    [cardButton setTitle:card.contents forState:UIControlStateNormal];
}
于 2013-02-22T18:12:11.573 回答
0
[button setTitle:@"S" forState:UIControlStateSelected];
        [button setTitle:@"D|S" forState:UIControlStateSelected|UIControlStateDisabled];

setTitle forUIControlStateSelected在两种情况下会使编译器感到困惑。有机会同时执行这两个条件。尝试更改第二行中的代码..祝您编码愉快

于 2013-02-22T05:23:14.063 回答