UIButton -setTitle:forState:似乎不起作用

问题描述:

我试图动态更新UIButtonIBOutletCollection的标题。我希望选择当标题设置为UIButton -setTitle:forState:似乎不起作用

  • 字母“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 

[button setTitle:@"S" forState:UIControlStateSelected]; 
     [button setTitle:@"D|S" forState:UIControlStateSelected|UIControlStateDisabled]; 

为的setTitle UIControlStateSelected在两种情况下使编译器混淆。有机会一次执行两种情况。尝试更改第二行代码..有一个快乐编码

+0

我在参考中没有看到任何其他方式。有没有其他方法可以做到这一点? – ydmm 2013-02-22 15:31:47

在尝试了很多不同的事情后,我得到它的唯一方法是如下。但这是一种C风格的逻辑,并改变了选定和禁用的UIButton控制状态的含义。这绝对是一个黑客:(

//  [cardButton setTitle:card.contents 
//     forState:UIControlStateSelected|UIControlStateDisabled]; 
if(cardButton.selected && !cardButton.enabled) { 
    [cardButton setTitle:card.contents forState:UIControlStateNormal]; 
} 

它不工作,因为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]; 

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