1

我正在使用url數組來加載圖像集合視圖。滾動收藏視圖時圖像正在變化。如何解決這個問題?UICollection查看細胞圖像在水平滾動時發生變化

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString *cellIdentifier = @"RecentProductCell"; 
    RecentProductCell *recentCell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath]; 

      recentCell.recentProductImg.image = nil; 
      dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{ 
       NSString *imageurl = [[latestProducts valueForKey:@"image"]objectAtIndex:indexPath.item]; 
       NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:imageurl]]; 

       dispatch_sync(dispatch_get_main_queue(), ^{ 
        recentCell.recentProductImg.image = [UIImage imageWithData:imageData]; 
       }); 
      }); 

    } 
+1

你重用你的細胞,並有取得處理異步發生。獲取數據後,將數據存儲在集合中,並嘗試使用indexpath.row訪問它們,以在每次重用單元時獲取確切的數據。 – erenkabakci

+0

好的,謝謝...... – Lokesh

回答

0

更換dispatch_sync(dispatch_get_main_queue(), ^{ recentCell.recentProductImg.image = [UIImage imageWithData:imageData]; });

dispatch_sync(dispatch_get_main_queue(), ^{ 
       if (imageData) 
       { 
        UIImage *urlImage = [[UIImage alloc] initWithData:imageData]; 
        RecentProductCell *recentCell = (id)[collectionView cellForItemAtIndexPath:indexPath]; 
        if (recentCell) 
         [recentCell.recentProductImg setImage:urlImage]; 
       } 
      }); 

讓我知道這對你的作品。

+0

我試過你的代碼,但仍然出現這個問題.. – Lokesh

0
cell.imageView.image = nil; 
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul); 
    dispatch_async(queue, ^(void) { 

     NSString *imageurl = [[latestProducts valueForKey:@"image"]objectAtIndex:indexPath.item]; 
      NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:imageurl]]; 

     UIImage* image = [[UIImage alloc] initWithData:imageData]; 
     if (image) { 
      dispatch_async(dispatch_get_main_queue(), ^{ 
       if (cell.tag == indexPath.row) { 
        cell.imageView.image = image; 
        [cell setNeedsLayout]; 
       } 
      }); 
     } 
    }); 

寫代碼的CollectionView

的方法的cellForRowAtIndexPath