2016-03-03 65 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它从我的项目中复制而来 –