views:

240

answers:

2

Im just fiddling around with small apps, trying to learn the SDK and ObjC 2.

Im trying to display an image randomly and I keep finding different ways up displaying a picture. I have uploaded the picture into the SDKs resources folder.

Anyway, here is my code. Can someone steer me in the right direction.

#import "randomViewController.h"

@implementation randomViewController


//not sure if this is the right way to do it really.
NSArray *comImage = [NSArray arrayWithObjects:
      [UIImage imageNamed:@"rock.png"],
      [UIImage imageNamed:@"paper.png"],
      [UIImage imageNamed:@"scissors.png"],
      nil];


- (IBAction) randButton {
 int text = rand() % 3;
 switch (text) {
  case 0:
   textView.text = @"Rock";
   break;
  case 1:
   textView.text = @"Paper";
   break;
  case 2:
   textView.text = @"Scissors";
   break;
  default:
   break;
 }
}
+1  A: 

I would do it this way:

NSArray *myImageNames = [NSArray arrayWithObjects:@"rock.png", @"paper.png", @"scissors.png", nil];
int index = arc4random() % [myImageNames count];

UIImage *myImage = [UIImage imageNamed:[myImageNames objectAtIndex:index]];
myUIImageView.image = myImage;

Obviously you can hold on to myImageNames so you don't have to recreate it every run if you deem it worthwhile.

Edit:
Got it. See the updated code. It assumes you have already added a UIImageView called myUIImageView to your view. I assume you know how to do this if you already have a UIButton on the screen.

To add a UIImageView:

Declare the UIImageView *myUIImageView in your header.
Place this in your viewDidLoad assuming you use an xib:

myUIImageView = [[UIImageView alloc] initWithFrame:CGRectMake(x, y, width, height)];
[self.view addSubview:myUIImageView];

Replace x, y, width and height with the appropriate values. They will determine where in the view the UIImageView appears and how large it is.

David Kanarek
So, am i replacing the "blah, foo, bar" with the image names like "rock.png" etc?and do i put it all in the -(IBAction)?
Yes, and yes. It's a little unclear what you are doing though, as you never use your images in the above code.
David Kanarek
Basically what I want to do is display a random picture when I push the "button". Its acting as the computers choice for the rock paper scissors. Im just not sure how to go about it and I figured this would be the best way to do it. Im just starting to learn it.
+1 this is how I'd do it.
Dave DeLong
you would think I would know how to do that, but looks can be deceiving ha ha. Im just learning the relationships between the different classes and methods. Getting a feel of it all. Thanks for all the help.
A: 

To display images, you want to add a UIImageView and set its image property to whatever UIImage you want. Look at David's answer to see how to get a random image using objectAtIndex:, then set the image property of your image view to that.

Ian Henry