nateicon
nateicon

Reputation: 3

UIButton not showing my UIbuttons background images for Array

The Dice is a button and when you touch it it rolles the dice and show the result on the dice button. 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

Answers (3)

LeNI
LeNI

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

Midhun MP
Midhun MP

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

Anil Varghese
Anil Varghese

Reputation: 42977

Use like this

[_diceButton setBackgroundImage:_diceArray[index] forState:UIControlStateNormal];  

Since your _diceArray contains UIImage's not image names

Upvotes: 1

Related Questions