Search code examples
iosobjective-cuiimageviewuibuttonarc4random

choose one button from 4 custom buttons with images


I have 4 images in 4 buttons: imag01.jpg, imag02.jpg, imag03.jpg, imag04.jpg and 4 sounds: sound01.aifc, sound02.aifc, sound03.aifc, sound04.aifc.

I am generating 4 buttons like this:

UIButton *oneButton = [UIButton buttonWithType:UIButtonTypeCustom];
[oneButton setTitle:@"1" forState:UIControlStateNormal];
[oneButton setTitle:@"1" forState:UIControlStateHighlighted];

[oneButton setImage:[UIImage imageNamed:@"imag01.jpg"] forState:UIControlStateNormal];
[oneButton setImage:[UIImage imageNamed:@"imag01.jpg"] forState:UIControlStateHighlighted];
oneButton.frame = CGRectMake(20, 100, 140, 100);

[scrMain addSubview:oneButton];

I want to generate a random number from 1 to 4, (for example 3), play the sound related to it (sound03.aifc) and ask the user to press the correct button for that sound (imag03.jpg).

How can I make a link between the buttons and the sounds?


Solution

  • Do this:

    • Assign different values from 0 to 3 to the tag property of each button.

    • Put the sounds in an array.

    • Generate a random integer between 0 and 3, inclusive. Use that as an index to retrieve a sound from the array. Play that sound.

    • Enable the 4 buttons and ask the user to tap the corresponding button.

    • If the tag property of the button matches the number you selected, HOORAY! Good job, user!

    • Else, TOO BAD! Try again.