UICollectionView Cell Tapped时显示按钮

时间:2016-12-21 07:07:22

标签: ios swift uicollectionview uicollectionviewcell

我有一个图像,当用户在该图像上点击两次时,我会显示一个带有勾号的按钮,好像用户勾选了该图像一样。我首先从故事板中设置隐藏按钮。

我正在使用此

进行单元格点击
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if collectionView == self.subOptionsCollectionView{
        let imageNamed = "\(customizeOptionSelected[indexPath.row])"

        shirtImage.image = UIImage(named: imageNamed)

        let tap = UITapGestureRecognizer(target: self, action: #selector(doubleTapped))
        tap.numberOfTapsRequired = 2
        collectionView.addGestureRecognizer(tap)
    }
}
func doubleTapped() {
    print("Double Tap")
}

但是如何显示该刻度/按钮?

2 个答案:

答案 0 :(得分:4)

将您的代码放入cellForRowAtIndexPath而不是didSelect并禁用collectionView的userInteraction,然后您可以在doubleTapped中将按钮的isHidden属性设置为true,但是您必须改变这样的功能(Swift3):

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

并像这样更改选择器:

UITapGestureRecognizer(target: self, action: self.doubleTapped(selectedIndex: indexPath))

还有另一种解决方案:

将您的代码放在cellForRowAtIndexPath而不是didSelect中,然后您可以在doubleTapped中将按钮的isHidden属性设置为true,但您必须更改此功能(Swift2) :

func doubleTapped(sender: AnyObject) {
     let buttonPosition: CGPoint = sender.convertPoint(CGPointZero, toView: self.collectionView)
     let indexPath: NSIndexPath = self.collectionView.indexPathForRowAtPoint(buttonPosition)!
     //you have the selected cell index
     let cell = self.collectionView.cellForItemAtIndexPath(indexPath)
     //now you have the cell and have access to the button

}

并添加如下手势:

let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.doubleTapped(_:)))
cell.addGestureRecognizer(tapGesture)

答案 1 :(得分:1)

Swift 4更新:

  @IBAction func doubleTap(_ sender: UITapGestureRecognizer) {

        let buttonPosition: CGPoint = sender.location(in: self.collectionView)
        guard let indexPath = self.collectionView?.indexPathForItem(at: buttonPosition) else { return }

        print ("doubleTap on cell at: ", indexPath)

        let cell = self.collectionView.cellForItem(at: indexPath)
        // now you have the cell and have access to the button
    }