Can't believe it was this simple, but here it is:
[Monster1 setImage:[KanaCharacters objectAtIndex:imageDisplay]];
All it needed was brackets.
Question
When I try to load a UIImageView with an image (either a specific image or an image from an array), my UIImageView just shows blank with running the app; no image at all. I'm not getting any syntax errors. Below you'll see that I tried two different assignments, one direct and one using an array, and neither worked. The NSLog confirms that a number is being stored in my imageDisplay variable. Any ideas? What am I missing?
- (void)viewDidLoad
{
KanaCharacters = [[NSArray alloc] initWithObjects:[UIImage imageNamed:@"a.png"],
[UIImage imageNamed:@"i.png"],
[UIImage imageNamed:@"u.png"],
[UIImage imageNamed:@"e.png"],
[UIImage imageNamed:@"o.png"],
[UIImage imageNamed:@"ka.png"],
[UIImage imageNamed:@"ki.png"],
[UIImage imageNamed:@"ku.png"],
[UIImage imageNamed:@"ke.png"],
[UIImage imageNamed:@"ko.png"],
nil];
int imageDisplay = arc4random_uniform([KanaCharacters count]);
NSLog(@"%d", imageDisplay); //3
Monster1.image = [[UIImage alloc] initWithCGImage:(__bridge CGImageRef)([UIImage
imageWithContentsOfFile:@"e.png"])];
// Monster1 = [[[UIImageView alloc]initWithFrame:(CGRectMake(49, 49, 45, 45))]
initWithImage:[KanaCharacters objectAtIndex:imageDisplay]];
Solution 2
Can't believe it was this simple, but here it is:
[Monster1 setImage:[KanaCharacters objectAtIndex:imageDisplay]];
All it needed was brackets.
OTHER TIPS
If you want Monster1
image to come from the array kanaCharacters
with the index number from imageDisplay
wouldn't you do this?
NSArray *array = [NSArray arrayWithObjects:@"a",@"b",@"c", nil]; //Setup array
int imageDisplay = arc4random_uniform([array count]); //Find random int from array count
UIImageView *monster1 = [[UIImageView alloc] initWithFrame:CGRectMake(10, 10, 100, 50)]; //Setup UIImageView
monster1.image = [UIImage imageNamed:array[imageDisplay]]; //Display image which is randomly selected from array
[self.view addSubview:monster1]; //Add image to view