使用 UITapGestureRecognizer 配置位置?

问题描述

override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view
        let tap = UITapGestureRecognizer(target: self,action: #selector(doubleTapped))
        tap.numberOfTapsrequired = 2
        view.addGestureRecognizer(tap)
    
    }
    
    @objc func doubleTapped(sender: UITapGestureRecognizer) {
        let indexPath = self.collectionView.indexPathForItem(at: sender.location(in: sender.view))

        if let unwrapped = indexPath {

出于某种原因,这里的 indexPath 始终为零。有人看到我代码中的错误吗?

解决方法

您需要在集合视图中获取点击位置,而不是超级视图。

使用let indexPath = self.collectionView.indexPathForItem(at: sender.location(in: self.collectionView))