1

I want to create an effect so that my collectionviewcell (which has one imageview as IBOutlet) will load its image with a random delay. So for example, cell #1 will have its image shown in 2 seconds, while #2 will take 1 second, cell #3 will take 4 seconds ... etc.

How would I do this? I heard about using NSOperationQueue at cellForRowAtIndexPath but not sure how to implement.

Terry Bu
  • 889
  • 1
  • 14
  • 31

2 Answers2

1

If your images are already available, you could try giving a random delay in your cellForItemAtIndexPath method:

UIImage *theImage = ...; //get your image
int maxDelay = 4;
int delayInSeconds = arc4random() % maxDelay;
cell.imageView.image = theImage;
cell.imageView.alpha = 0;
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
      cell.imageView.alpha = 1;
});

If your image is not available in memory, and it needs to be loaded, you may want to look at this post on how to load the image asynchronously:

Community
  • 1
  • 1
jlw
  • 3,166
  • 1
  • 19
  • 24
0

You could have a method on the cell's subclass for setting the image, then within that method call another method with a random delay to actually set the UIImageView's image. Something like this:

- (void)delayedSetBackgroundImage:(UIImage *)image
{
    [self performSelector:@selector(setBackgroundImage:) withObject:image afterDelay:(arc4random() % 5)];
}

- (void)setBackgroundImage:(UIImage *)image
{
    _myImageView.image = image;
}

So then in cellForRowAtIndexPath you would call delayedSetBackgroundImage: and the cell itself would take care of the rest.

sfeuerstein
  • 913
  • 7
  • 21