How Can I get Xcode to randomize a picture?
So I have been searching around the internet fo methods to randomly select then display an image. And so far I have this in my .m viewcontroller:
#import "classgenViewController.h"
@implementation classgenViewController
@synthesize images, randomStrings;
- (void)viewDidLoad {
[super viewDidLoad];
self.randomStrings = [NSArray arrayWithObjects:@"Frag.png",
@"Semtex.png",
@"Tomahawk.png",
nil];
}
- (IBAction)showRandomString {
UIImageView *images = [randomStrings objectAtIndex: (arc4random() % [randomStrings count])];
}
- (void)viewDidUnload {
// Release any retained su开发者_如何学编程bviews of the main view.
// e.g. self.myOutlet = nil;
self.images = nil;
}
- (void)dealloc {
[self.images release];
[self.randomStrings release];
[super dealloc];
}
@end
but the *images says it is an unused variable. How can I use it. It is declared in my .h, I have used the (property, nonatomic) method on it, as well as synthesized it. Help?
You're just assigning images
variable and not actually doing anything with it. Also - you're creating instance of UIImageView
class while assigning an actual string to it. Do you have UIImageView
outlet assigned to your UIViewController
? If so - just assign an UIImage
to it like this:
- (IBAction)showRandomString {
NSString *randomImageFilename = [randomStrings objectAtIndex: (arc4random() % [randomStrings count])];
UIImage *image = [UIImage imageNamed:randomImageFilename];
uiImageViewOutlet.image = image;
}
First you declared it as a property. Then you overrode that by declaring it as a local variable in showRandomStrings. That local variable is never used. To assign the value to the instance variable declared in the .h file, remove the "UIImageView *" before it.
Also, you seem to want to assign an NSString to UIImageView pointer. That will only end in tears.
Maybe you want to do something like this:
UIImage* newImage = [UIImage imageNamed:<your random string here>];
images.image = newImage;
Where "images" is presumably a UIImageView* that you set up in .h and which you configured in the Interface Builder.
For me as a beginner, I would use a method that is not professional at all, but it works :)
First of all in the interface builder add the imageViews you want along with the images. and make them hidden.
Then add an array with objects referring to the images you have, than use
randomImage = [nameOfArray objectAtIndex:arc4random() % [nameOfArray count]];
then add some if statements along with a single line to make the imageView appear, for example:
if ([randomImage isEqual:@"image1"]) {
image1.hidden = NO;
}
I tried that method before, and it worked.
Good luck
精彩评论