ios - 单击 Collection View 单元格时 UITapGestureRecognizer 崩溃应用程序

标签 ios swift uigesturerecognizer

我试图在我的 Collection View 中允许用户交互。我决定尝试实现 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")

    }

最佳答案

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

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

关于ios - 单击 Collection View 单元格时 UITapGestureRecognizer 崩溃应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59438815/

相关文章:

iphone - 是否可以根据国家/地区更改捆绑显示名称?

ios - 多个标签 xAxis iOS-Charts

ios - 如何设置 UIScrollView 来动态排列内容?

operators - 无法为元组定义一元运算符

ios - 检查按下了哪个 gestureRecognizer

ios - UIGestureRecognizer 和 UITextView

ios - 如何从 UITableView 单元格获取数据到全局变量

ios - 条形按钮项目不会连接到退出

ios - 在 TableView 中移动行

ios - 如何创建一个计算器,通过一个输入填充多个具有不同值的标签字段?