【问题标题】:UITapGestureRecognizer crashing app when clicking on collection view cell单击集合视图单元格时,UITapGestureRecognizer 崩溃应用程序
【发布时间】:2019-12-21 18:30:29
【问题描述】:

我正在尝试在我的收藏视图中允许用户交互。我决定尝试实施 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")

    }

【问题讨论】:

  • 可能还有堆栈跟踪和更详细的失败消息,其中任何一个都可能会有所帮助。你能查一下吗?
  • 如何获得更详细的失败消息?我是 Xcode 的新手,只能看到调试器控制台 atm 中的内容。与堆栈跟踪一样,您希望在控制台中键入“bt”时出现什么?
  • 只是好奇,您使用手势识别器而不是默认的单元格选择方法是否有原因?
  • 你应该使用 didSelectItemAtIndexPath: 集合视图委托的方法而不是自定义的 tapGesture。
  • @udbhateja didSelectItemAt() 不起作用。我的 collectionview 不响应用户输入。我检查了所有用户交互字段,它们都设置为 true,但它仍然不起作用。你知道怎么做才能使 didSelectItemAt() 起作用吗?

标签: ios swift uigesturerecognizer


【解决方案1】:

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

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

【讨论】:

  • didSelectItemAt 不起作用。我的收藏视图不响应用户交互。你知道为什么会发生这种情况吗?
  • 也许你还在某个地方点击了手势识别器,它会阻止选择单元格。检查他们,这应该是问题。
  • 以防万一,集合视图是否分配了delegate
  • @GlebA。集合视图委托被分配了 collectionview.delegate = self。还有其他方法吗?
  • @EmreDeğirmenci 在手势识别器之前我试图做 didSelectItemAt() 。 didSelectItemAt() 根本不起作用。你有什么其他的想法吗?
【解决方案2】:

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

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

例如<yourColletionViewName>.delegate = self

以上可以分配到viewDidLoad()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-02
    • 1970-01-01
    • 2018-11-13
    相关资源
    最近更新 更多