我试图动态地更新UIButtons的IBOutletCollection的标题.我期望标题被设置
>选择和’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: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
解决方法
它不工作,因为IB设置归因标题而不是标题.
改为:
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];
(第二个选项不会保留格式.)