2013-03-17 48 views
1

我使用這個代碼的圖像使用自定義單元格UITableView的滾動凍結加載從服務器

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 

static NSString *CellIdentifier = @"CustomCell"; 

CustomCell *cell = (CustomCell *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 

if (cell == nil) { 

    NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"CustomCell" owner:self options:nil]; 
    for (id currentObject in topLevelObjects) { 
     if ([currentObject isKindOfClass:[CustomCell class]]) { 
      cell = (CustomCell *) currentObject; 
      break; 
     } 
    } 

    NSString *tempString = [arrayThumbs objectAtIndex:indexPath.row]; 
    NSURL *imageURL = [NSURL URLWithString:tempString]; 
    NSData *imageData = [NSData dataWithContentsOfURL:imageURL]; 
    UIImage *image = [UIImage imageWithData:imageData]; 
    cell.img.image = image; 

} 

return cell; 
} 

與上面的代碼在一個UITableView加載我的圖片,有向上和向下滾動時是沒有問題的,但圖像顯示不正確,一些圖像在表格中重複出現,例如,如果數組包含從1到10的10個圖像,並且該數組的順序是正確的,那麼我得到的圖像就像1,2 ,3,4,3,1,10,8,9

但當我使用此代碼

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 

static NSString *CellIdentifier = @"CustomCell"; 

CustomCell *cell = (CustomCell *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 

if (cell == nil) { 

    NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"CustomCell" owner:self options:nil]; 
    for (id currentObject in topLevelObjects) { 
     if ([currentObject isKindOfClass:[CustomCell class]]) { 
      cell = (CustomCell *) currentObject; 
      break; 
     } 
    } 

} 

NSString *tempString = [arrayThumbs objectAtIndex:indexPath.row]; 
    NSURL *imageURL = [NSURL URLWithString:tempString]; 
    NSData *imageData = [NSData dataWithContentsOfURL:imageURL]; 
    UIImage *image = [UIImage imageWithData:imageData]; 
    cell.img.image = image; 

return cell; 
} 

圖像被責令罰款,沒有重複,但是當我滾動表,然後滾動回頂部2或3秒

任何想法表凍結的底部如何解決這個問題?

數組包含類似http://www.website.com/image.jpg

自定義單元格的圖像鏈接含有IBOutlet中的UIImageView 60X60,並從服務器加載圖像也是60X60

回答

8

試試下面的代碼下載圖像中的線。

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ 
    NSString *tempString = [arrayThumbs objectAtIndex:indexPath.row]; 
    NSURL *imageURL = [NSURL URLWithString:tempString]; 
    NSData *imageData = [NSData dataWithContentsOfURL:imageURL]; 
    UIImage *image = [UIImage imageWithData:imageData]; 
    dispatch_async(dispatch_get_main_queue(), ^{ 
     cell.img.image = image; 
    }); 
}); 
+0

工作完美;)非常感謝你 – aLFaRSi 2013-03-17 08:34:22