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
         }           
    }       
}

相关文章

UITabBarController 是 iOS 中用于管理和显示选项卡界面的一...
UITableView的重用机制避免了频繁创建和销毁单元格的开销,使...
Objective-C中,类的实例变量(instance variables)和属性(...
从内存管理的角度来看,block可以作为方法的传入参数是因为b...
WKWebView 是 iOS 开发中用于显示网页内容的组件,它是在 iO...
OC中常用的多线程编程技术: 1. NSThread NSThread是Objecti...