загрузка изображения в UITableViewCell асинхронно - PullRequest
1 голос
/ 11 ноября 2011

Что такое супер очень простой способ загрузки изображения в UITableViewCell, асинхронно, с учетом imageURL, без необходимости создавать подклассы UITableViewCell, то есть: стандартный UITableViewCell

Ответы [ 3 ]

1 голос
/ 11 ноября 2011

Самый простой способ, который я знаю, это использовать библиотеку SDWebImage.Вот ссылка, которая объясняет, как использовать библиотеку SDWebImage для асинхронной загрузки аватаров.

SDWebImage является расширением ImageView.Вот использование:

// load the avatar using SDWebImage
    [cell.imageView setImageWithURL:[NSURL URLWithString:tweet.profileImageUrl]
                   placeholderImage:[UIImage imageNamed:@"grad_001.png"]];

А вот ссылка на статью:

Реализация поиска в Твиттере

1 голос
/ 11 ноября 2011

В вашем .m включите целевое время выполнения c:

#import <objc/runtime.h>

В верхней части раздела @implementation определите статическую константу для использования ниже:

static char * const myIndexPathAssociationKey = "";

В вашем cellForRowAtIndexPath добавьте следующий код:

// Store a reference to the current cell that will enable the image to be associated with the correct  
// cell, when the image subsequently loaded asynchronously. Without this, the image may be mis-applied
// to a cell that has been dequeued and reused for other content, during rapid scrolling. 
objc_setAssociatedObject(cell,
                         myIndexPathAssociationKey,
                         indexPath,
                         OBJC_ASSOCIATION_RETAIN);

// Load the image on a high priority background queue using Grand Central Dispatch.
// Can change priority by replacing HIGH with DEFAULT or LOW if desired.
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0);
dispatch_async(queue, ^{
    UIImage *image = ... // Obtain your image here.

    // Code to actually update the cell once the image is obtained must be run on the main queue.
    dispatch_async(dispatch_get_main_queue(), ^{
        NSIndexPath *cellIndexPath = (NSIndexPath *)objc_getAssociatedObject(cell, myIndexPathAssociationKey);
        if ([indexPath isEqual:cellIndexPath]) {
        // Only set cell image if the cell currently being displayed is the one that actually required this image.
        // Prevents reused cells from receiving images back from rendering that were requested for that cell in a previous life.
            [cell setImage:image];
        }
    });
}];

Наконец, для поддержки наилучшей производительности при быстрой прокрутке на старых устройствах, вы можете сначала загрузить самые последние запрошенные изображения ... для этого см. этот поток для асинхронной загрузки изображений ячеек с использованием последнего в порядке первого вне стека и GCD .

0 голосов
/ 11 ноября 2011

Вы можете использовать тему. Сначала поместите кнопку в словарь. Тогда используйте поток. Наконец в методе setImage: вы можете разместить изображение.

NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];

        [dictionary setObject:url forKey:@"url"];
        [dictionary setObject:image forKey:@"image"];
        [NSThread detachNewThreadSelector:@selector(setImage:) 
                                 toTarget:self 
                               withObject:dictionary];
...