2017-06-04 40 views
2

我有很多不同图片的收藏视图,我希望当图片被点击时,边框就会出现。UITapGestureRecognizer不改变CollectionViewCell的内容。 Swift

我制作了一个自定义单元格,并将一个UICollectionViewCell与imageView嵌入到另一个视图(这是大纲)的图片。所以我建立了一个可以获取索引的UITapGestureRecognizer,但是当我将外部视图设置为boder时,它不起作用。

这是我的手机:

import UIKit 

class PicViewCell: UICollectionViewCell { 


    @IBOutlet weak var imageView: UIImageView! 


    @IBOutlet weak var imageOutline: UIView! 


} 

这是我UICollectionViewController:

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { 
      let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! PicViewCell 

      // Configure the cell 

    let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTap(sender:))) 

      cell.imageOutline.addGestureRecognizer(tapGesture) 




     return cell 

下面是tapGesture方法

func handleTap(sender: UITapGestureRecognizer) { 
     print("tap") 

     if let indexPath = self.collectionView?.indexPathForItem(at: sender.location(in: self.collectionView)) { 

      let cell = collectionView?.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! PicViewCell 

    cell.imageOutline.layer.borderWidth = 5 


     } else { 
      print("") 
     } 


    } 

回答

2

在你handleTap程序,你”重新调用错误的方法来检索单元格。你想cellForItem(at:)将检索现有的小区或返回nil如果不是屏幕上:

let cell = collectionView?.cellForItem(at: indexPath) as! PicViewCell 

替代的解决方案

如果要修改你正在利用该视图,您可以访问它作为senderview

func handleTap(sender: UITapGestureRecognizer) { 
    if let imageOutline = sender.view as? UIImageView { 
     imageOutline.layer.borderWidth = 5 
    } 
} 

注意:在这两种解决方案中,您应该在绘制单元格时更新模型,以便如果该单元格从屏幕滚动然后返回到屏幕上,则可以使用该模型数据设置单元格的轮廓正确地在您的重写collectionView(_:cellForItemAt:)

+0

这很有用,非常感谢。但正如你所说,当我滚动回到单元格时,它不会保持轮廓。我已经更新了模型,但它仍然没有停留概述。谢谢 – RJB

+0

在您将可重用单元出列后,在'collectionView(_:cellForItemAt:):'中,如果您的模型表示该单元已被点击,则需要将图层borderWidth设置为5。 – vacawama

+0

谢谢,你帮了我一吨。 – RJB