2016-03-03 66 views
0

現在我有一個UICollectionView(水平滾動)哪些單元格包含UIImage。我使用這個功能來顯示UIImage過濾器,就像Instagram一樣。但是當我滾動查看實現過濾器後圖像的外觀時 - 它會凍結。我如何才能讓它流暢如Instagram?如何異步加載CollectionView細胞圖像?

我的代碼:

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { 
    let cell: imageFilterCell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! imageFilterCell 

    NSOperationQueue.mainQueue().addOperationWithBlock {    
     cell.imageView.image = self.applyFilterTo(self.image!, filter: self.filtersImages[indexPath.row]) 
     cell.imageView.layer.cornerRadius = 5 
     cell.imageView.layer.masksToBounds = true 
     cell.filterLabel.text = self.filtersLabels[indexPath.row] 
    } 

    return cell 
} 

其中applyFilter()實現了一個過濾器,我的形象。

任何解決方案使滾動平滑,並防止凍結?

+1

而是在主線程上的圖像應用過濾器,使用後臺線程。一旦你收到過濾圖像,然後獲得主隊列和顯示圖像。 – Surjeet

+1

你可以在這裏使用SDWebImage。讓它從https://github.com/rs/SDWebImage –

+0

@Surjeet所以,你建議使用:'let img = self.applyFilterTo(self.image!,filter:self.filtersImages [indexPath.row])'和後來的'NSOperationQueue.mainQueue()。addOperationWithBlock {cell.imageView.image = img'}'。是? –

回答

2

試試這個

let queue = NSOperationQueue() 

     let op1 = NSBlockOperation {() -> Void in 

      let img1 = self.applyFilterTo(self.image!, filter: self.filtersImages[indexPath.row]) 

      NSOperationQueue.mainQueue().addOperationWithBlock({() -> Void in 
       cell.imageView.image = img1 
      }) 
     } 


queue.addOperation(op1); 
cell.imageView.layer.cornerRadius = 5 
     cell.imageView.layer.masksToBounds = true 
     cell.filterLabel.text = self.filtersLabels[indexPath.row] 
+0

這正是我想要的!謝謝! –

+0

隨時,請致電 – techloverr

+1

@JohnDoe這隻適用於,如果內容不會滾動。但是,您表示您的視圖將水平滾動。它不起作用,因爲單元格將被重用 - 到圖像完成時,單元現在可以被重用來顯示另一行。所以,這段代碼包含一個bug。 – CouchDeveloper

0

試試這個

dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0); 
    dispatch_async(queue, ^(void) { 

     NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:parsedData[@"imageURL"]]; 

     UIImage* image = [[UIImage alloc] initWithData:imageData]; 
     if (image) { 
      dispatch_async(dispatch_get_main_queue(), ^{ 

        cell.imageView.image = image; 
        [cell setNeedsLayout]; 

      }); 
     } 
    }); 
+0

您可以添加代碼在那裏你設置標籤 - 並解釋爲什麼這個代碼將起作用。 – CouchDeveloper

+0

嘿@CouchDeveloper它從我的項目中複製而來 –