Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lazy loading in uicollectionview

here is the code for my collectionview it is showing records but loading really please tell me how can i implement lazy loading on this i also have a placeholder pic in my project

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    CollectionViewCell* cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"MJCell" forIndexPath:indexPath];

// Setup image name
    NSString *url = [[rssOutputData objectAtIndex:indexPath.row]xmllink];
    UIImage *img = nil;
    NSData *data = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:url]];
    img = [[UIImage alloc] initWithData:data];

    cell.MJImageView.image = img;
    return cell;
}

right now it is working but very very slow.

like image 402
Vix Hunk Avatar asked Jan 09 '23 16:01

Vix Hunk


2 Answers

It's pretty easy to do lazy loading using GCD.

    // Create a queue for the operations
    dispatch_queue_t queue = dispatch_queue_create("photoList", NULL);

    // Start getting the data in the background
    dispatch_async(queue, ^{
        NSData* photoData = [NSData dataWithContentsOfURL:[NSURL URLWithString:object.photoURL]];
        UIImage* image = [UIImage imageWithData:photoData];

        // Once we get the data, update the UI on the main thread
        dispatch_sync(dispatch_get_main_queue(), ^{
           cell.photoImageView.image = image;
        });
    });
like image 119
Amit Avatar answered Jan 11 '23 23:01

Amit


The easiest way to implement that is use SDWebImage library, it does right what you need. There is UIImageView category that will allow you to modify code for that:

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    CollectionViewCell* cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"MJCell" forIndexPath:indexPath];

    // Setup image name
    NSString *url = [[rssOutputData objectAtIndex:indexPath.row]xmllink];
    [cell.MJImageView sd_setImageWithURL:[NSURL URLWithString:url]];
    return cell;
}
like image 30
Azat Avatar answered Jan 12 '23 01:01

Azat