I have store 10 images in NSArray.
In UIViewController i placed 6 UIImageView,and given the outlet in .h file.
I need to select any 6 images from the array how to do?
And need to display the images in UIImageView.
- (void)viewDidLoad {
[super viewDidLoad];
images=[[NSMutableArray alloc]initWithObjects:[UIImage imageNamed:#"Navarre-Family-Eye-Care-Navarre-Florida-Optometrist-Santa-Christmas-Toy-Safety.jpg"],[UIImage imageNamed:#"Christmas-Wallpapers-HD-Picture.jpg"],[UIImage imageNamed:#"Christmas-Wallpaper-jesus-9413550-1024-768.jpg"],[UIImage imageNamed:#"tree.jpg"],[UIImage imageNamed:#"luxury-christmas-napkins-father-christmas-1635-p.jpg"],[UIImage imageNamed:#"Navarre-Family-Eye-Care-Navarre-Florida-Optometrist-Santa-Christmas-Toy-Safety.jpg"],[UIImage imageNamed:#"Christmas-Wallpapers-HD-Picture.jpg"],[UIImage imageNamed:#"Christmas-Wallpaper-jesus-9413550-1024-768.jpg"],[UIImage imageNamed:#"tree.jpg"],[UIImage imageNamed:#"luxury-christmas-napkins-father-christmas-1635-p.jpg"], nil];
NSString *dd=[NSString stringWithFormat:#"%#", images];
NSLog(#"%#",dd);
}
- (void)setImagesForImageViews:(NSArray<UIImageView*>*)viewsArray fromArray:(NSArray<UIImage*>*)imageArray {
if(images == nil || viewsArray == nil || viewsArray.count > images.count) {
return; // early return
}
NSMutableArray* randomImageArray = [NSMutableArray arrayWithCapacity:viewsArray.count];
while (randomImageArray.count < viewsArray.count) {
UIImage* image;
do {
NSUInteger random = (NSUInteger)arc4random_uniform(images.count);
image = [imageArray objectAtIndex:random];
} while ([randomImageArray containsObject:image]);
[randomImageArray addObject:image];
}
[viewsArray enumerateObjectsUsingBlock:^(UIImageView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
obj.image = [randomImageArray objectAtIndex:idx];
}];
}
in .h file
#import
#interface memory_test : UIViewController
{
NSMutableArray *images;
}
#property(weak,nonatomic)IBOutlet UIImageView *b1;
#property(weak,nonatomic)IBOutlet UIImageView *b2;
#property(weak,nonatomic)IBOutlet UIImageView *b3;
#property(weak,nonatomic)IBOutlet UIImageView *b4;
#property(weak,nonatomic)IBOutlet UIImageView *b5;
#property(weak,nonatomic)IBOutlet UIImageView *b6;
Lets suppose(as the question is not clear), you want to set random images to imageviews from an array of images. The challenge here is to find the random image, non-repeating, ofcourse from an array.
I haven't tested the code, but something like this should work:
- (void)viewDidLoad {
[super viewDidLoad];
NSArray* images = [self imagesArray];
NSArray* views = [self imageViewsArray];
[self setRandomImagesForImageViews:views fromArray:images];
}
- (NSArray<UIImage*>*)imagesArray {
return #[[UIImage imageNamed:#"Navarre-Family-Eye-Care-Navarre-Florida-Optometrist-Santa-Christmas-Toy-Safety.jpg"],[UIImage imageNamed:#"Christmas-Wallpapers-HD-Picture.jpg"],[UIImage imageNamed:#"Christmas-Wallpaper-jesus-9413550-1024-768.jpg"],[UIImage imageNamed:#"tree.jpg"],[UIImage imageNamed:#"luxury-christmas-napkins-father-christmas-1635-p.jpg"],[UIImage imageNamed:#"Navarre-Family-Eye-Care-Navarre-Florida-Optometrist-Santa-Christmas-Toy-Safety.jpg"],[UIImage imageNamed:#"Christmas-Wallpapers-HD-Picture.jpg"],[UIImage imageNamed:#"Christmas-Wallpaper-jesus-9413550-1024-768.jpg"],[UIImage imageNamed:#"tree.jpg"],[UIImage imageNamed:#"luxury-christmas-napkins-father-christmas-1635-p.jpg"]];
}
- (NSArray<UIImageView*>*)imageViewsArray {
return #[_b1, _b2, _b3, _b4, _b5, _b6];
}
- (void)setRandomImagesForImageViews:(NSArray<UIImageView*>*)viewsArray fromArray:(NSArray<UIImage*>*)imageArray {
if(imageArray == nil || viewsArray == nil || viewsArray.count > imageArray.count) {
return; // early return
}
NSMutableArray* randomImageArray = [NSMutableArray arrayWithCapacity:viewsArray.count];
while (randomImageArray.count < viewsArray.count) {
UIImage* image;
do {
NSUInteger random = (NSUInteger)arc4random_uniform(imageArray.count);
image = [imageArray objectAtIndex:random];
} while ([randomImageArray containsObject:image]);
[randomImageArray addObject:image];
}
[viewsArray enumerateObjectsUsingBlock:^(UIImageView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
obj.image = [randomImageArray objectAtIndex:idx];
}];
}
You can remove your images array declaration from your header file if you are not using it again in the class.
FOR SWIFT
class ViewController: UIViewController {
//array with ImageView
#IBOutlet var imageViews: [UIImageView]!
//array with Image
lazy var imagesArray = [UIImage]()
override func viewDidLoad() {
super.viewDidLoad()
//initiate image
let imageOne :UIImage = #imageLiteral(resourceName: "exchange")
let imageTwo :UIImage = #imageLiteral(resourceName: "indexPhone")
let imageThree :UIImage = #imageLiteral(resourceName: "indexCheer")
let imageFour :UIImage = #imageLiteral(resourceName: "indexTrade")
let imageFive :UIImage = #imageLiteral(resourceName: "indexWashMachine")
//add image to array
imagesArray = [imageOne,imageTwo,imageThree,imageFour,imageFive]
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//Action for Button
#IBAction func randomSelect(_ sender: Any) {
//temporary array for images
var tempImageArray = imagesArray
for imageView in imageViews{
// get random index for array images
let index = Int(arc4random_uniform(UInt32(tempImageArray.count)))
// set random image for ImageView
imageView.image = tempImageArray[index]
// remove arleady added Image from temporary array
tempImageArray.remove(at: index)
}
}
}
FOR OBJECTIVE-C
#interface ViewController ()
//array with ImageView
#property (strong, nonatomic) IBOutletCollection(UIImageView) NSArray *imageViews;
//array with Image
#property (strong, nonatomic) NSArray* imagesArray;
- (IBAction)randomSelect:(id)sender;
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
//initiate image
UIImage *imageOne = [UIImage imageNamed:#"exchange"];
UIImage *imageTwo = [UIImage imageNamed:#"indexCheer"];
UIImage *imageThree = [UIImage imageNamed:#"indexPhone"];
UIImage *imageFour = [UIImage imageNamed:#"indexTrade"];
UIImage *imageFive = [UIImage imageNamed:#"indexWashMachine"];
//Initiate array with image
self.imagesArray = [NSArray arrayWithObjects:imageOne,imageTwo,imageThree,imageFour,imageFive, nil];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)randomSelect:(id)sender {
//temporary array for images
NSMutableArray* tempImageArray = [[NSMutableArray alloc]initWithArray:self.imagesArray];
for (UIImageView* imageView in self.imageViews){
// get random index for array images
int index = arc4random()%(tempImageArray.count-1);
// set random image for ImageView
imageView.image = [tempImageArray objectAtIndex:index];
// remove arleady added Image from temporary array
[tempImageArray removeObjectAtIndex:index];
}
}
Related
Hi everyone iam new in objective c, now i try to create the app like "What's the word". I find this tutorial and lerned it as well as i can. But i have some problems. I want when i click on buttons the currentTitle replace the lable in placesView. Button click method in LettersView.m named as "displayChar". I have success in getting currentTitle but now i don't know how to pass it to GameController and paste text on "places".
I will be grateful for any help!
Here is my code
LettersView.h
#import <UIKit/UIKit.h>
#class LettersView;
#protocol LetterClickDelegateProtocol <NSObject>
-(void)letterView:(LettersView*)letterView addChar:(NSString *)addChar;
#end
#interface LettersView : UIImageView
#property (strong, nonatomic, readonly) NSString* letter;
#property (assign, nonatomic) BOOL isMatched;
#property (strong, nonatomic) NSString *clickLetter;
#property (weak, nonatomic) id<LetterClickDelegateProtocol> clickDelegate;
#property (strong, nonatomic) UIButton *lblChar;
-(instancetype)initWithLetter:(NSString*)letter andSideLength:(float)sideLength;
#end
LettersView.m
#import "LettersView.h"
#import "config.h"
#implementation LettersView{
NSInteger _xOffset, _yOffset;
}
- (id)initWithFrame:(CGRect)frame
{
NSAssert(NO, #"Use initWithLetter:andSideLength instead");
return nil;
}
-(instancetype)initWithLetter:(NSString*)letter andSideLength:(float)sideLength
{
//the letter background
UIImage* img = [UIImage imageNamed:#"btn_letter#2x.png"];
//create a new object
self = [super initWithImage:img];
if (self != nil) {
//resize the letters
float scale = sideLength/img.size.width;
self.frame = CGRectMake(0,0,img.size.width*scale, img.size.height*scale);
UIButton *lblChar = [[UIButton alloc] initWithFrame:self.bounds];
lblChar.tintColor = [UIColor blackColor];
lblChar.backgroundColor = [UIColor clearColor];
[lblChar setTitle:letter forState:UIControlStateNormal];
[lblChar addTarget:self action:#selector(displaychar:)forControlEvents:UIControlEventTouchUpInside];
[self addSubview:lblChar];
self.isMatched = NO;
_letter = letter;
self.userInteractionEnabled = YES;
}
return self;
}
-(void)displayChar:(id)sender {
UIButton *lblChar = (UIButton *)sender;
NSLog(#" The button's title is %#.", lblChar.currentTitle);
_clickLetter = lblChar.currentTitle;
if (self.clickDelegate) {
[self.clickDelegate letterView:self addChar:lblChar.currentTitle];
}
NSLog(#"hu %#", _clickLetter);
}
PlacesView.h
// PlacesView.m
#import "PlacesView.h"
#import "config.h"
#implementation PlacesView
-(id)initWithFrame:(CGRect)frame {
NSAssert(NO, #"Use initwithletter");
return nil;
}
-(instancetype)initWithLetter:(NSString *)letter andSideLength:(float)sideLength
{
UIImage *img = [UIImage imageNamed:#"btn_input#2x.png"];
self = [super initWithImage: img];
if (self != nil) {
self.isMatched = NO;
float scale = sideLength/img.size.width;
self.frame = CGRectMake(0, 0, img.size.width*scale, img.size.height*scale);
//bullshit time
_fieldForLetter = [[UILabel alloc] initWithFrame:self.bounds];
_fieldForLetter.textAlignment = NSTextAlignmentCenter;
_fieldForLetter.textColor = [UIColor blackColor];
_fieldForLetter.backgroundColor = [UIColor clearColor];
_fieldForLetter.text = #"*"; // if button pressed button title placed here.
[self addSubview:_fieldForLetter];
_letter = letter;
}
return self;
}
#end
GameController.m
#import "GameController.h"
#import "config.h"
#import "LettersView.h"
#import "PlacesView.h"
#import "AppDelegate.h"
#implementation GameController {
//tile lists
NSMutableArray* _letters;
NSMutableArray* _places;
}
-(instancetype)init {
self = [super init];
if (self != nil) {
self.points = [[PointsController alloc] init];
self.audioController = [[AudioController alloc] init];
[self.audioController preloadAudioEffects: kAudioEffectFiles];
}
return self;
}
-(void)dealRandomWord {
NSAssert(self.level.words, #"Level not loaded");
// random word from plist
NSInteger randomIndex = arc4random()%[self.level.words count];
NSArray* anaPair = self.level.words[ randomIndex ];
NSString* word1 = anaPair[1]; // answer
NSString* word2 = anaPair[2]; // some letters
_helpstr = anaPair[3]; // helper
NSLog(#"qweqweq %# %#" , word1 , word2);
NSInteger word1len = [word1 length];
NSInteger word2len = [word2 length];
NSLog(#"phrase1[%li]: %#", (long)word1len, word1);
NSLog(#"phrase2[%li]: %#", (long)word2len, word2);
//calculate the letter size
float letterSide = ceilf( kScreenWidth*0.9 / (float)MAX(word1len, word2len) ) - kTileMargin;
//get the left margin for first letter
float xOffset = (kScreenWidth - MAX(word1len, word2len) * (letterSide + kTileMargin))/2;
//adjust for letter center
xOffset += letterSide/2;
float yOffset = 1.5* letterSide;
// init places list
_places = [NSMutableArray arrayWithCapacity: word1len];
// create places
for (NSInteger i = 0; i<word1len; i++){
NSString *letter = [word1 substringWithRange:NSMakeRange(i, 1)];
if (![letter isEqualToString:#" "]) {
PlacesView* place = [[PlacesView alloc] initWithLetter:letter andSideLength:letterSide];
place.center = CGPointMake(xOffset + i*(letterSide + kTileMargin), kScreenHeight/4);
[self.gameView addSubview:place];
[_places addObject: place];
}
}
//init letters list
_letters = [NSMutableArray arrayWithCapacity: word2len];
//create letter
for (NSInteger i=0;i<word2len;i++) {
NSString* letter = [word2 substringWithRange:NSMakeRange(i, 1)];
if (![letter isEqualToString:#" "]) {
LettersView* letv = [[LettersView alloc] initWithLetter:letter andSideLength:letterSide];
letv.center = CGPointMake(xOffset + i * (letterSide + kTileMargin), kScreenHeight); // "/3*4"
if (i > 6) {
letv.center = CGPointMake(-5.15 * xOffset + i * (letterSide + kTileMargin), kScreenHeight + yOffset); // "/3*4"
}
letv.clickDelegate = self;
[self.gameView addSubview:letv];
[_letters addObject: letter];
}
}
}
-(void)letterView:(LettersView *)letterView addChar:(NSString *)addChar
{
PlacesView* placesView = nil;
for (PlacesView* pl in _places) {
//if (CGRectContainsPoint(pl.frame, pt)) {
if () {
//placesView = pl;
placesView.fieldForLetter.text = letterView.lblChar.currentTitle;
break;
}
}
//1 check if target was found
if (placesView!=nil) {
//2 check if letter matches
if ([placesView.letter isEqualToString: letterView.letter]) {
[self placeLetter:letterView atTarget:placesView];
[self.audioController playEffect: kSoundLetterTap];
self.points.points += self.level.coinsPerLvl; //ne nado tak
NSLog(#"Current points %d" , self.points.points);
[self checkForSuccess];
} else {
[self.audioController playEffect:kSoundFail];
[self addAlert:#"ne success" andMessage:#"You lose!" andButton:#"eshe cyka"];
}
}
}
-(void)placeLetter:(LettersView*)letterView atTarget:(PlacesView*)placeView {
placeView.isMatched = YES;
letterView.isMatched = YES;
letterView.userInteractionEnabled = NO;
}
-(void)checkForSuccess {
for (PlacesView* p in _places) {
//no success, bail out
if (p.isMatched==NO) return;
}
NSLog(#"ya!");
[self addAlert:#"Success" andMessage:#"You win!" andButton:#"eshe cyka"];
[self.audioController playEffect:kSoundSuccess];
}
-(void)addAlert: (NSString *)addTitle andMessage: (NSString *)alertMessage andButton: (NSString *)alertButton {
dispatch_async(dispatch_get_main_queue(), ^{
UIWindow* window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
window.rootViewController = [UIViewController new];
window.windowLevel = UIWindowLevelAlert + 1;
UIAlertController *alert = [UIAlertController alertControllerWithTitle: addTitle message:alertMessage preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *defaultAction= [UIAlertAction actionWithTitle:alertButton style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
window.hidden = YES;
}];
[alert addAction:defaultAction];
[window makeKeyAndVisible];
[window.rootViewController presentViewController:alert animated:YES completion:nil];
});
}
#end
Your GameController needs to keep a reference to PlacesView. It can also assign the action into LettersView so when the button in LettersView is pressed, the GameController will fetch it and perform an action in PlacesView. GameController is what both the other classes have in common, so it can handle any actions between them.
Another option is to use NSNotificationCenter and post a message in LettersView when the button is pressed, and listen for it in PlacesView.
Yet anther way is using a delegates where GameController makes sure that PlacesView is set as the delegate. When LettersView's button is pressed, it will call the delegate method which PlacesView listens to.
I'd go with first option.
I am trying to include MWPhotoBrowser in my project
When its used as given in the sample it working fine.
But when a new viewcontroller is subclassed from MWPhotoBrowser, photos are not loaded except empty black theme.
Delegate methods are not getting called. As the controller is subclass of MWPhotoBrowser, I assume there is no need to set it explicitly.
Storyboard is used and the nib class in it is set.
.h file
#interface MDRPhotoViewerController : MWPhotoBrowser
{
NSMutableArray *_selections;
}
#property (nonatomic, strong) NSMutableArray *photos;
#property (nonatomic, strong) NSMutableArray *thumbs;
#property (nonatomic, strong) NSMutableArray *assets;
#property (nonatomic, strong) NSMutableIndexSet *optionIndices;
#property (nonatomic, strong) UITableView *tableView;
#property (nonatomic, strong) ALAssetsLibrary *ALAssetsLibrary;
- (void)loadAssets;
#end
**.m file **
- (void)viewWillAppear:(BOOL)animated
{
NSMutableArray *photos = [[NSMutableArray alloc] init];
NSMutableArray *thumbs = [[NSMutableArray alloc] init];
//mwphotobrowser options setup
BOOL displayActionButton = YES;
BOOL displaySelectionButtons = NO;
BOOL displayNavArrows = NO;
BOOL enableGrid = YES;
BOOL startOnGrid = NO;
BOOL autoPlayOnAppear = NO;
//loading data
NSArray *photosDataArray = [MDRDataController GetPhotos]; //creating array
for (NSString *urlString in photosDataArray) { //Formating the data source for images
NSString *urlFullString = [NSString stringWithFormat:#"%#%#",KBASEURL,urlString];
//Photos
[photos addObject:[MWPhoto photoWithURL:[NSURL URLWithString:urlFullString]]];
//thumbs
[thumbs addObject:[MWPhoto photoWithURL:[NSURL URLWithString:urlFullString]]];
}
// Options
self.photos = photos;
self.thumbs = thumbs;
// Create browser
self.displayActionButton = displayActionButton;
self.displayNavArrows = displayNavArrows;
self.displaySelectionButtons = displaySelectionButtons;
self.alwaysShowControls = displaySelectionButtons;
self.zoomPhotosToFill = YES;
self.enableGrid = enableGrid;
self.startOnGrid = startOnGrid;
self.enableSwipeToDismiss = NO;
self.autoPlayOnAppear = autoPlayOnAppear;
[self setCurrentPhotoIndex:0];
// Test custom selection images
// browser.customImageSelectedIconName = #"ImageSelected.png";
// browser.customImageSelectedSmallIconName = #"ImageSelectedSmall.png";
// Reset selections
if (displaySelectionButtons) {
_selections = [NSMutableArray new];
for (int i = 0; i < photos.count; i++) {
[_selections addObject:[NSNumber numberWithBool:NO]];
}
}
self.title = #"Phots";
//[self reloadData];
}
Debugging performed
Considering the image template of mwphotobrowser, tried reloading the code.
Shifted the code between viewwillappear and viewdidload.
Doesn't MWPhotoBrowser support this way or am i doing it wrong ?
For those who stumble upon this later...
If you look at MWPhotoBrowser.m you'll see various initializers:
- (id)init {
if ((self = [super init])) {
[self _initialisation];
}
return self;
}
- (id)initWithDelegate:(id <MWPhotoBrowserDelegate>)delegate {
if ((self = [self init])) {
_delegate = delegate;
}
return self;
}
- (id)initWithPhotos:(NSArray *)photosArray {
if ((self = [self init])) {
_fixedPhotosArray = photosArray;
}
return self;
}
- (id)initWithCoder:(NSCoder *)decoder {
if ((self = [super initWithCoder:decoder])) {
[self _initialisation];
}
return self;
}
The problem is there's no awakeFromNib initializer. Simplest solution is to fork the project and create the awakeFromNib initializer.
I have an array of NSStrings, what I'd like to use as a source for a UIImageView's image names.
When the user taps a button I load a new image - next object from the array - into the same image view, that would be the final goal. Actually I have a working, but silly solution, and that's not what I want. I would like to load the string names from an array to the UIImage, because this if statement can grow really big with 30-40 object and that's not so reliable. I'm not so fine with for loops so I would really appreciate if somebody could show me how can I get the same result with a loop or any other way.
- (IBAction)changeImage:(id)sender {
if (!self.userImageView.image) {
UIImage *image = [UIImage imageNamed:#"img1.png"];
self.userImageView.image = image;
self.currentDisplayedImageString = #"img1.png";
// self.currentDisplayedImageString is an ivar, type of NSString
}
else {
if ([self.currentDisplayedImageString isEqualToString:#"img1.png"]) {
UIImage *image = [UIImage imageNamed:#"img2.png"];
self.userImageView.image = image;
self.currentDisplayedImageString = #"img2.png";
}
if ([self.currentDisplayedImageString isEqualToString:#"img2.png"]) {
UIImage *image = [UIImage imageNamed:#"img3.png"];
self.userImageView.image = image;
self.currentDisplayedImageString = #"img3.png";
}
// AND SO ON...
}
}
something like:
#interface ViewController ()
#property (strong, nonatomic) UIImageView *imageView;
#property (strong, nonatomic) NSArray *imageNames;
#property (assign, nonatomic) int currentImageIndex;
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.imageNames = #[#"img1", #"img2", #"img3", #"img4"];
self.currentImageIndex = -1;
}
- (void)changeImage {
if (++self.currentImageIndex == self.imageNames.count) {
self.currentImageIndex = 0;
}
self.imageView.image = [UIImage imageNamed:self.imageNames[self.currentImageIndex]];
}
#end
hope it helps!
If your image names are in fact "img1," "img2," "img3," etc. you don't actually need an array to store them since the names essentially index themselves. Instead I'd recommend doing something like:
- (IBAction)changeImage:(id)sender {
if (!self.userImageView.image ||
[self.currentDisplayedImageString isEqualToString:#"img40.png"]) {
self.currentDisplayedImageString = #"img1.png";
}
else {
// Get the filename's numerical index by parsing out the numerical component
NSString *index = [[self.currentDisplayedImageString componentsSeparatedByCharactersInSet:
[[NSCharacterSet decimalDigitCharacterSet] invertedSet]]
componentsJoinedByString:#""];
// "Increment" the currentDisplayedImageString
self.currentDisplayedImageString = [NSString stringWithFormat:#"img%#.png", index];
}
// Then update the image
UIImage *image = [UIImage imageNamed:currentDisplayedImageString];
self.userImageView.image = image;
}
I am using this code to generate random image to UIImageView. When I click the button, it apears another image. I would like to ask you how to create four imageviews - click button -> apears four different random images.
ViewController.h
#interface ViewController : UIViewController {
IBOutlet UIImageView *imageView;
// IBOutlet UIImageView *imageView2;
}
-(IBAction) randomImage;
ViewController.m
- (IBAction) randomImage {
NSArray *images = [[NSArray alloc] initWithObjects:#"image1.jpg", #"image2.jpg", #"image3.jpg", #"image4.jpg", nil];
int count = [images count]
int index = arc4random() % count;
imageView.image = [UIImage imageNamed:[images objectAtIndex:index]];
// imageView2.image = ....
}
I created four imageViews in storyboard and I was trying something like above // imageView2.image... but it it not the right solution :-)
Thank you for your help
Code to list 4 random image:
NSMutableArray *images = [[NSMutableArray alloc] initWithArray: #[#"image1.jpg", #"image2.jpg", #"image3.jpg", #"image4.jpg"]];
int countImg = images.count;
for (int i = 0; i < countImg; i++) {
NSInteger index = arc4random() % images.count;
NSLog(#"Image%d name = %#",i , [images objectAtIndex:index]);
[images removeObjectAtIndex:index];
}
Rather than using IBOutlet UIImageView *imageView;, use IBOutletCollection(UIImageView) NSArray *imageViews; and connect all of your image views to this.
Then, in your code:
- (IBAction) randomImage {
NSArray *images = [[NSArray alloc] initWithObjects:#"image1.jpg", #"image2.jpg", #"image3.jpg", #"image4.jpg", nil];
NSInteger count = [images count];
for (UIImageView *imageView in self.imageViews) {
NSInteger index = arc4random() % count;
imageView.image = [UIImage imageNamed:[images objectAtIndex:index]];
}
}
I am having some trouble loading images from a file into an array. I have used a combination of questions I have found on here, and am out of ideas.... I am new to objective-c and rusty on the rest.
My viewDidLoad simply calls my showPics method, and for testing sake I have the _imgView just show the image at position 1 in the array.
It could very well be a problem with the way I am showing the images as well. I have a ViewController and one ImageView (titled: imgView) in my Storyboard.
here is my showPics method:
-(void)showPics
{
NSArray *PhotoArray = [[NSBundle mainBundle] pathsForResourcesOfType:#"jpg" inDirectory:#"Otter_Images"];
NSMutableArray *imgQueue = [[NSMutableArray alloc] initWithCapacity:PhotoArray.count];
for (NSString* path in PhotoArray)
{
[imgQueue addObject:[UIImage imageWithContentsOfFile:path]];
}
UIImage *currentPic = _imgView.image;
int i = -1;
if (currentPic != nil && [PhotoArray containsObject:currentPic]) {
i = [PhotoArray indexOfObject:currentPic];
}
i++;
if(i < PhotoArray.count)
_imgView.image= [PhotoArray objectAtIndex:1];
}
Here is my viewDidLoad:
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
[self showPics];
}
Here is my ViewController.h
#interface ViewController : UIViewController
#property (weak, nonatomic) IBOutlet UIImageView *imgView;
#end
Please let me know if you need anything else and thank you in advance!
In your showPics method, other than the initial 'for-loop', all of your references to PhotoArray should instead be references to imgQueue. PhotoArray is a list of pathnames. imgQueue is the array of actual UIImage objects.
-(void)showPics {
NSArray *PhotoArray = [[NSBundle mainBundle] pathsForResourcesOfType:#"jpg" inDirectory:#"Otter_Images"];
NSMutableArray *imgQueue = [[NSMutableArray alloc] initWithCapacity:PhotoArray.count];
for (NSString* path in PhotoArray) {
[imgQueue addObject:[UIImage imageWithContentsOfFile:path]];
}
UIImage *currentPic = _imgView.image;
int i = -1;
if (currentPic != nil && [imgQueue containsObject:currentPic]) {
i = [imgQueue indexOfObject:currentPic];
}
i++;
if(i < imgQueue.count) {
_imgView.image = [imgQueue objectAtIndex:1];
}
}