Set Individual Title of UIButtons in IBOutletCollection

倾然丶 夕夏残阳落幕 提交于 2019-12-23 05:20:03

问题


Does anybody know how to set the title of each individual button in an array of buttons using an IBOutletCollection? This is what I have tried, but the code sets the title of all the buttons. I have connected the outlet to the buttons and set their respective tags.

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

回答1:


If you only want to set the title of the button you've clicked on, get rid of the for loop,

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



回答2:


Try this:

for (int i = 0; i < [buttonCollection count]; ++i)
{
    [((UIButton*)self.buttonCollection[i]) setTitle: [NSString stringWithFormat: @"%d button", i] forState: UIControlStateNormal];
}


来源:https://stackoverflow.com/questions/22867120/set-individual-title-of-uibuttons-in-iboutletcollection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!