Derek Hewitt
Derek Hewitt

Reputation: 775

Image not showing in my UICollectionView

So I've been looking for a solution to this issue, but can't seem to find anything. I have an array that I load with image paths using the below method

- (IBAction)btnPictures:(id)sender {

// Create the next view controller.
ImageGalleryViewController *galleryViewController = [[ImageGalleryViewController alloc] initWithNibName:@"ImageGalleryViewController" bundle:nil];


// Search for paths and get users home directory
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                     NSUserDomainMask, YES);
// get path at first index (in case multiple returned
NSString *documentsDirectory = [paths objectAtIndex:0];

NSArray *dirContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentsDirectory error:nil];
NSArray *files = [dirContents filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"pathExtension IN %@", @"png"]];

// Pass the selected object to the new view controller.
[galleryViewController setImageArray:files];

// Push the view controller.
[self.navigationController pushViewController:galleryViewController animated:YES];

}

That image array is then sent to the below method in my UICollectionViewController

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView       cellForItemAtIndexPath:(NSIndexPath *)indexPath{

ImageGalleryViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ImageGalleryViewCell" forIndexPath:indexPath];

NSLog(@"Image at index %@", [imageArray objectAtIndex:indexPath.row]);

[cell.galleryImage setImage:[UIImage imageWithContentsOfFile:[imageArray objectAtIndex:indexPath.row]]];

[cell setBackgroundColor:[UIColor whiteColor]];
return cell;
}

I verified the objectAtIndex is returning a valid image name through my NSLog, but for some reason the cell is not displaying it.

Any help is greatly appreciated, thanks in advance.

Upvotes: 0

Views: 1380

Answers (2)

Gaurav Singh
Gaurav Singh

Reputation: 1997

The array returned by -contentsOfDirectoryAtPath: of NSFileManager doesn't provide the full file path but just the name of files and directories. You have to append each values in the array to the path to your Document Directory.

Something like this:

NSString *documentsDirectoryPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
NSString *imagePath = [documentsDirectoryPath stringByAppendingPathComponent:[imageArray objectAtIndex:indexPath.row]];
UIImage *image = [UIImage imageWithContentsOfFile:imagePath];

Upvotes: 2

Fahri Azimov
Fahri Azimov

Reputation: 11770

I suspect, you are not initialising any cells before using (dequequing) one. Initialise your cell, and try again. Good Luck!

PS: by initialising I mean, alloc init your cell.

Upvotes: 0

Related Questions