单击集合视图单元格时UITapGestureRecognizer崩溃的应用程序

时间:2019-12-21 18:30:29

标签: ios swift uigesturerecognizer

我正在尝试允许用户在我的收藏夹视图中进行交互。我决定尝试实现UITapGestureRecognizer来执行此操作。我尝试将UITapGestureRecognizer添加到collectionview本身以及collectionview单元中。两种方法都会使应用程序崩溃。这是我将UITapGestureRecognizer添加到单元格的方式。


func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {


        let cell = collectionview.dequeueReusableCell(withReuseIdentifier: "userCell", for: indexPath) as! UserCell



          cell.userImage.sd_setImage(with: URL(string: self.user[indexPath.row].imagePath))

           cell.nameLabel.text = self.user[indexPath.row].username
           cell.userID = self.user[indexPath.row].userID


        let singleTap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "segueToProfile:")
               singleTap.numberOfTapsRequired = 1
               singleTap.numberOfTouchesRequired = 1
        cell.addGestureRecognizer(singleTap)

        return cell
    }

当我点击单元格时,在AppDelegate中会得到一个SIGABRT。错误消息显示为“以类型为NSException的未捕获异常终止”。我究竟做错了什么。 UITapGestureRecognizer。

这是我的segueToProfile函数:


    func segueToProfile(gesture: UITapGestureRecognizer) {
//        if(recognizer.state == UIGestureRecognizer.State.ended){
//            print("myUIImageView has been tapped by the user.")
//        }
        print("hell world")

    }

2 个答案:

答案 0 :(得分:0)

如果您使用didSelectItemAt的collectionView方法,则代码库看起来可读且可维护。

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
currentViewController.performSegue(withIdentifier: "YourSegueName", sender: nil)
}

答案 1 :(得分:0)

首先,我将摆脱tapgesturerecognizer,因为didSelectItem应该处理您要完成的工作。话虽如此,为了使它起作用,您必须:

  1. 删除tapgesturerecognizer
  2. 确保将集合视图委托设置为self。

例如<yourColletionViewName>.delegate = self

以上可以分配给viewDidLoad()