0

有人知道如何使用 IBOutletCollection 设置按钮数组中每个按钮的标题吗?这是我尝试过的,但代码设置了所有按钮的标题。我已将插座连接到按钮并设置它们各自的标签。

.h file
@property (nonatomic, retain) IBOutletCollection(UIButton) NSArray *buttonCollection;

.m file
- (IBAction)switchAction:(id)sender {

    for (UIButton *btn in buttonCollection) {
        if (btn.tag == 0) {
            [btn setTitle:@"1st Button" forState:UIControlStateNormal];
        } else if (btn.tag == 1) {
            [btn setTitle:@"2nd Button" forState:UIControlStateNormal];
       } else if (btn.tag == 2) {
           [btn setTitle:@"3rd Button" forState:UIControlStateNormal];
       }
}
4

2 回答 2

1

如果您只想设置您单击的按钮的标题,请摆脱 for 循环,

- (IBAction)switchAction:(UIButton *)sender {

     if (sender.tag == 0) {
          [sender setTitle:@"1st Button" forState:UIControlStateNormal];
     } else if (sender.tag == 1) {
          [sender setTitle:@"2nd Button" forState:UIControlStateNormal];
     } else if (sender.tag == 2) {
         [sender setTitle:@"3rd Button" forState:UIControlStateNormal];
}
于 2014-04-04T16:32:12.470 回答
0

尝试这个:

for (int i = 0; i < [buttonCollection count]; ++i)
{
    [((UIButton*)self.buttonCollection[i]) setTitle: [NSString stringWithFormat: @"%d button", i] forState: UIControlStateNormal];
}
于 2014-04-04T15:52:28.923 回答