简体   繁体   中英

UIButton Changes Variable When Tapped?

I have multiple UIButton s - redButton , greenButton , yellowButton , etc. When you tap one of these buttons, another UIImageView will change its image accordingly to, say, redImage , greenImage , yellowImage .

How would I implement this? I've tried this:

[self.redButton addTarget:self action:@selector(changeColour:) forControlEvents:UIControlEventTouchUpInside];

[self.greenButton addTarget:self action:@selector(changeColour:) forControlEvents:UIControlEventTouchUpInside];

[self.yellowButton addTarget:self action:@selector(changeColour:) forControlEvents:UIControlEventTouchUpInside];

And in changeColour :

-(void)changeColour:(id)sender{
  // How do I know which button was pressed?
}

All I'd like to know is which button was pressed. Preferrably, I would like it so when a button is tapped, it changes an int variable called colour . So, something like:

if greenButton was tapped, change int = 1 . If redButton was tapped, change int = 2 .

I've searched StackOverflow and Google and the results say to include a method in the @selector of action: . So what would I have to put in changeColour to recognise which button called changeColour ?

-(void)changeColour:(id)sender
{
    if (sender == self.redButton) {
        // redButton action
    } else if (sender == self.greenButton) {
        // greenButton action
    } else if (sender == self.yellowButton) {
        // yellowButton action
    }
}

to do these kinds of identification the sender attribute was introduced.

You can use tag property of UIView. ie

self.redButton.tag = 1;
self.yellowButton.tag = 2;

In the chnageColor method, you can retrieve the same.

-(void)changeColour:(id)sender
{
  // How do I know which button was pressed?
  UIButton *btn = (UIButton *)sender;
  if(btn.tag == 1)
  //Red is pressed..
  //and you can check for other tags...
}

Tap on the UIButton in the Interface Builder, and change the tag property of it in Attributes Inspector . Then access this tag property programmatically in your view controller to get to know which button was pressed.

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