ios – Selector获取indexPath UICollectionView Swift 3.0

前端之家收集整理的这篇文章主要介绍了ios – Selector获取indexPath UICollectionView Swift 3.0前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图在单击两次时获取单元格的indexPath.
我在Selector中传递参数,但是它给出了错误.
这是什么格式?
func collectionView(_ collectionView: UICollectionView,cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    if  let subOptioncell : SubOptionsCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: subOptionsCVReuseIdentifier,for: indexPath) as! SubOptionsCollectionViewCell

          let imageNamed = "\(customizeOptionSelected[indexPath.row])"
          subOptioncell.subOptionsImage.image = UIImage(named: imageNamed)

          let tap =  UITapGestureRecognizer(target: self,action: #selector(doubleTapped(sender: indexPath)))
          tap.numberOfTapsrequired = 2
          collectionView.addGestureRecognizer(tap)   

          return subOptioncell
    }
}

func doubleTapped(sender: IndexPath) {
    print("Double Tap")
}

解决方法

首先,您将tapGesture添加到collectionView而不是subOptioncell.

它应该是:

subOptioncell.addGestureRecognizer(tap)

代替:

collectionView.addGestureRecognizer(tap)

您无法使用UIGestureRecognizer的选择器传递其他实例,您可以传递的唯一实例是UI(Tap)GestureRecognizer.如果你想要那个单元格的indexPath,你可以尝试这样.首先将TapGesture的选择器设置为这样.

let tap =  UITapGestureRecognizer(target: self,action: #selector(doubleTapped(sender:)))

现在的方法应该是:

func doubleTapped(sender: UITapGestureRecognizer) {
    if let cell = sender.view as? SubOptionsCollectionViewCell,let indexPath = self.collectionView.indexPath(for: cell) {
         print(indexPath)
    }       
}

编辑:如果要在单元格双击上显示/隐藏图像,则需要使用单元格的indexPath处理它,因为它首先声明一个IndexPath实例并在cellForItemAt indexPath中使用它.

var selectedIndexPaths = IndexPath()

func collectionView(_ collectionView: UICollectionView,cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    //Your code 
    //Now add below code to handle show/hide image
    cell.subOptionSelected.isHidden = self.selectedIndexPaths != indexPath
    return cell
}

现在,在UITapGestureRecognizer的doubleTapped操作中设置selectedIndexPath.

func doubleTapped(sender: UITapGestureRecognizer) {
    if let cell = sender.view as? SubOptionsCollectionViewCell,let indexPath = self.collectionView.indexPath(for: cell) {
         if self.selectedIndexPaths == indexPath {
             cell.subOptionSelected.isHidden = true
             self.selectedIndexPaths = IndexPath()
         }
         else {
             cell.subOptionSelected.isHidden = false
             self.selectedIndexPaths = indexPath
         }           
    }       
}
原文链接:https://www.f2er.com/iOS/335274.html

猜你在找的iOS相关文章