sender tag always return 1

I have a piano keyboard. Each button (key of the piano) has a different tag assigned in IB. The tag is used to identify each button so I can play the sound that belongs to that piano key. I connect each piano key to the following IBAction:

-(IBAction)playNoteFromKeyTouch:(id) sender{
    UIButton *pressedButton = sender;
    int tag = [pressedButton tag];
}

The value returned by [pressedButton tag] is always 1. I have tried different ways to get this, for example:

-(IBAction)playNoteFromKeyTouch:(id) sender{
    NSInteger tag = ((UIView*)sender).tag;
}

And simply:

-(IBAction)playNoteFromKeyTouch:(id) sender{
    int tag = [sender tag];
}

No matter what I do, even when I assign tags programatically to each piano key, I always get tag == 1. What could I be missing?

Upvotes: 1

Views: 446

Answers (2)

vikingosegundo
vikingosegundo

Reputation: 52227

I think, you should go with another approach. Create an Octave class, subclass your keys from UIView, add an octave property and an note property to the key.

alternatively you can have an array for every octave and check what index in what array the sender has to determine the note.

tags are nice, to identify a view loaded from a nib-file. for anything else proper object-orientated object handling is better!

Upvotes: 1

sevenflow
sevenflow

Reputation: 777

I put together a test project and verified that your code should be giving you the appropriate tag. Perhaps you overlooked something outside of the code. Try the following:

  • Verify you changed the proper .xib (iPhone instead of iPad, etc.)
  • Verify the tags are properly set in the .xib
  • Restart Xcode and verify that the tags are still set

Upvotes: 0

Related Questions