问题描述:

I'm trying to build photo gallery as a practice to learn IOS. The requirement was to get random images and make sure there're at least 2-images per row. I tried UICollectionView but it's not working as expected! Am I missing something?

Here's a link for the github repository

I'm calling the photosvie in ViewController.m like this

-(void)viewDidAppear:(BOOL)animated

{

[super viewDidAppear:animated];

[self presentViewController:[[PhotosGridView alloc] init] animated:YES completion:nil];

}

then the init method in PhotosGridView.m

-(PhotosGridView *)init {

NSLog(@"initalizin photos grid view");

UICollectionViewFlowLayout *aFlowLayout = [[UICollectionViewFlowLayout alloc] init];

[aFlowLayout setItemSize:CGSizeMake(150, 140)];

[aFlowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];

return [super initWithCollectionViewLayout:aFlowLayout];

}

To register the custom cell class I use this (recommended by a friend) in viewDidLoad method:

UINib *nibForTheCell = [UINib nibWithNibName:@"PhotosGridViewCell" bundle:nil];

[self.collectionView registerNib:nibForTheCell forCellWithReuseIdentifier:reuseIdentifier];

Then for binding each cell I use these methods in same file

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

PhotosGridViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];

NSLog(@"im in loading cell %li", (long)indexPath.row);

// Configure the cell

NSURL *baseURL = [NSURL URLWithString:[self generateURLString]];

[[cell imageView] sd_setImageWithURL:(baseURL) completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {

CGSize size = [self decideSize: image];

cell.frame = CGRectMake(cell.frame.origin.x, cell.frame.origin.y, size.width, size.height);

cell.imageView.hidden = false;

cell.activityIndicator.hidden = true;

// NSLog(@"\nImageSize: (%f, %f)", image.size.width, image.size.height);

// NSLog(@"\nCellSize: (%f, %f)", size.width, size.height);

}];

return cell;

}

-(NSString *) generateURLString {

int width = 250 + arc4random_uniform(600);

int height = 300 + arc4random_uniform(600);

return [NSString stringWithFormat:@"http://lorempixel.com/%i/%i/", width, height];

}

-(CGSize) decideSize: (UIImage *)image {

CGSize s;

int minWidth = (self.view.frame.size.width - 200) / 2;

s.width = MIN(minWidth, image.size.width);

if (s.width != image.size.width) {

s.height = (image.size.height * s.width) / image.size.width;

}

return s;

}

Here's a screenshot for how it looks like now

相关阅读:
Top