简体   繁体   中英

Call methods on UIButton objects in NSMutableArray Objective-C

I have an array called buttons which consists of UIButton objects. I populate it as follows:

for (int i=0; i<self.numButtons; i++) {
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
    [button setTitle:@"Title" forState:UIControlStateNormal];
    button.frame = CGRectMake(xCoord-40, y, 80, 20);
    [button setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    [button setTag:i];
    [self.buttons addObject:button];
    [self.view addSubview:button];
    y+= 45;
}

The action for these buttons is buttonAction. This action is supposed to change the color of the selected button. Here is how I have it implemented:

-(void) buttonAction:(id)sender{
    int num = (int)[sender tag];
    [[self.buttons objectAtIndex:num] setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    NSLog(@"%@", [self.buttons objectAtIndex:buttonClicked].titleLabel.text);
}

The result is that there is no color change. Even when I try to NSLog the title of the button it returns (null). So my question is how can I fix this but also how do I call methods on objects inside arrays? Any help would be appreciated. Thanks!

All evidence points to self.buttons being nil . Did you ever initialize it?

Somewhere you need a line like:

self.buttons = [NSMutableArray array];

Of course you could use the sender parameter to your buttonAction: method:

- (void)buttonAction:(UIButton *)button {
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
}

Note the change in the parameter.

I like to do this. Don't forget to use IBAction. It will help if you decide to use a nib or storyboard.

-(IBAction) buttonAction:(id)sender{
    [((UIButton*)sender) setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal]
    NSLog(@"%@", ((UIButton*)sender).titleLabel.text)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM