Reputation: 3
. So it will show the image of random 1-6 image of the dice on the button by touching the UIButton with a IBAction using a array and a random() to select from the array of images to desplay on the image background
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (IBAction)diceButton:(UIButton *)sender {
_diceArray=[NSMutableArray arrayWithObjects:
[UIImage imageNamed:@"Dice_1.png"],
[UIImage imageNamed:@"Dice_2.png"],
[UIImage imageNamed:@"Dice_3.png"],
[UIImage imageNamed:@"Dice_4.png"],
[UIImage imageNamed:@"Dice_5.png"],
[UIImage imageNamed:@"Dice_6.png"],nil];
int index = random() % 5 ;
for (int i = 0; i < [_diceArray count]; i++) {
[_diceButton setBackgroundImage:[UIImage imageNamed:[_diceArray objectAtIndex:index]] forState:UIControlStateNormal];
}
}
@end
Upvotes: 0
Views: 796
Reputation: 1184
hi you have two way to correct this program, first one change your array to
_diceArray=[NSMutableArray arrayWithObjects:
@"Dice_1.png",
@"Dice_2.png",
@"Dice_3.png",
@"Dice_4.png",
@"Dice_5.png",
@"Dice_6.png",nil];
or change
[_diceButton setBackgroundImage:[_diceArray objectAtIndex:index] forState:UIControlStateNormal];
Upvotes: 1
Reputation: 107211
You are storing UIImage
objects in the array so you can't call
[UIImage imageNamed:[_diceArray objectAtIndex:index]
So you need to use:
[_diceButton setBackgroundImage:[_diceArray objectAtIndex:index] forState:UIControlStateNormal];
My Suggestion : use setImage:
instead of setBackgroundImage:
for (int i = 0; i < [_diceArray count]; i++)
{
[_diceButton setImage:[_diceArray objectAtIndex:index] forState:UIControlStateNormal];
[_diceButton setImage:[_diceArray objectAtIndex:index] forState:UIControlStateNormal];
}
Upvotes: 0
Reputation: 42977
Use like this
[_diceButton setBackgroundImage:_diceArray[index] forState:UIControlStateNormal];
Since your _diceArray
contains UIImage
's not image names
Upvotes: 1