当UICollectionView Cell被点击时显示按钮

3

我有一张图片,当用户双击该图片时,我会显示一个带有勾号的按钮,就像用户已经勾选了该图片。我在Storyboard中首先将按钮设置为隐藏。

我使用以下代码来检测单元格的点击:

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

但是如何显示那个勾选框/按钮?


为什么你在did select方法中设置tapgesture?你必须在cell for row at indexpath方法中设置它。 - Ahmed Sahib
你需要重新加载集合视图以显示单元格中的最新更改。 - Amanpreet
不要重新加载,只需使用所选行并对特定单元格进行更改。 - Ahmed Sahib
首先,为什么要在didselect方法中编写tapgesture? - Ahmed Sahib
双击后仅启用并取消隐藏按钮。 - Nikhil Manapure
现在已经在CellForRow中实现了Tap手势。仍在尝试找出显示该按钮的方法。 - Nitesh
2个回答

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)

我该如何在这里调用单元格上的按钮? - Nitesh
1
不需要使用委托,您可以通过从发送者中提取UITapGesture的点来查找索引。 - Mina
@Mina,按钮在单元格内部。 - Nitesh
是的,这显示不正确。UITapGestureRecognizer(target:self,action:self.doubleTapped(selectedIndex:indexPath)) - Nitesh
您需要在您的模型上放置某种布尔值,以便滚动时其他单元格不会显示在其他随机单元格上。 - Zonily Jame
显示剩余6条评论

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
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接