Reputation:
Im using a UICollectionView to load images.
Following is my code. ImageArray will contain the url for each images that has to be loaded. and In my code, Im trying to give a round border around the entire collectionview
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *identifier = @"Cell";
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
UIImageView *recipeImageView = (UIImageView *)[cell viewWithTag:100];
CALayer* layer = cell.layer;
[layer setCornerRadius:4.0f];
[layer setBorderColor:[UIColor colorWithWhite:0.8 alpha:1].CGColor];
[layer setBorderWidth:1.0f];
if ([ImageArray count] >0){
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^(void) {
NSData *data0 = [NSData dataWithContentsOfURL: [NSURL URLWithString:[ImageArray objectAtIndex:indexPath.row]]];
UIImage *image = [UIImage imageWithData: data0];
dispatch_sync(dispatch_get_main_queue(), ^(void) {
recipeImageView.image = image;
});
});
}
[spinnerShow stopAnimating];
cell.layer.shouldRasterize = YES;
cell.layer.rasterizationScale = [UIScreen mainScreen].scale;
return cell;
}
The problem that im facing is that,
How can I sort this out?
Upvotes: 0
Views: 805
Reputation: 570
in UICollectionViewCell
is a method prepareForReuse
which you should override and set UIImageView
's image to nil
Upvotes: 1
Reputation: 753
UICollectionView
will reuse the existing cell. So there might be a possibility that your imageView
in collectionViewCell
will display the previous loaded image.
Its not a perfect solution, but give a try like passing nil
or default image to imageView
before starting downloading like
recipeImageView.image = nil;
before
if ([ImageArray count] > 0) {
Upvotes: 1
Reputation: 258
You are referencing the cell's tag but all cells have the same tag value of 100. This means that you are going to get unpredictable results and this is why your images keep changing.
Upvotes: 0
Reputation: 27428
You can set border and corner radius to collection view like,
collectionView.layer.borderWidth = 1.0;
collectionView.layer.backgroundColor = [UIColor colorWithWhite:0.8 alpha:1].CGColor;
collectionView.layer.cornerRadius = 4.0f;
And don't set it in cellForItemAtIndexPath
. Set it in viewdidload
, so that it loads once, otherqwise it will set everytime when cell will deque!
Second thing, as suggest in one comment you should use SDWebImage for caching the images.
Make sure you set right constraints if you are using autolayout.
Hope this will help :)
Upvotes: 0