I am populating a standard UITableViewCell with an image as follows:
cell.imageView.image = [UIImage imageNamed:@"someImageName.png"];
Is there a way to have “someImageName.png” be a random png image within my Xcode project? For the record, what I’d really like to do is put similar images in their own directory within the project – e.g. pets, faces, etc, and then depending on the table row select a random image from that directory.
I know I could rename the images using a scheme such as “image_0.png”, “image_1.png” … “image_n.png” and then use a random number x between 0..n to create “image_x.png” – but I’m curious if there’s a way just to retrieve a random .png image file without doing the renaming (or writing the files to local storage, then retrieving a random file from there)?
Thanks very much.
You’ll need to use the
- (NSArray *)pathsForResourcesOfType:(NSString *)extension inDirectory:(NSString *)subpath;method ofNSBundleclass.Then just take one random path from that array and get the image with
+(UIImage*)imageWithContentsOfFile::(NSString*)fileName;or+(UIImage*)imageWithData:(NSData*)imageData;and the+(NSData*)dataWithContentsOfURL:(NSURL *)url;