Search code examples
iosobjective-cuiimageviewsender

How do I use the sender argument to figure out what UIImageView was selected?


I have eight UIImageViews that I want to fade if the UITapGestureRecognizer that is associated with it is activated. I have the all recognizers hooked up to this IBAction:

- (IBAction)disableDie:(id)sender {

    NSLog(@"%@", sender);
    NSLog(@"%ld",[(UIGestureRecognizer *)sender view].tag);

}

I thought I could do it with a loop like this:

- (IBAction)disableDie:(id)sender {

    for (UIImageView *numberImage in self.diceOutletArray) {
        if (numberImage == sender) {
            numberImage.alpha = 0.65;
        }
    }

    NSLog(@"%@", sender);
    NSLog(@"%ld",[(UIGestureRecognizer *)sender view].tag);

}

But nothing happens to the UIImageView that was pressed, but the message's are printed. I have used the diceOutletArray in other loops and it works.


Solution

  • The sender is a UITapGestureRecognizer, not a UIImageView, and therefore numberImage == sender will never be true.

    Try this instead:

    - (IBAction)disableDie:(UIGestureRecognizer *)sender {
        for (UIImageView *numberImage in self.diceOutletArray) {
            if (numberImage == sender.view) {
                numberImage.alpha = 0.65;
                break;
            }
        }
    }
    

    You don't actually need the loop at all though, this would work fine as well:

    - (IBAction)disableDie:(UIGestureRecognizer *)sender {
        sender.view.alpha = 0.65;
    }