【问题标题】:touchesBegan not firing in UICollectionViewControllertouchesBegan 没有在 UICollectionViewController 中触发
【发布时间】:2015-11-08 01:40:06
【问题描述】:

我有一个布置一堆单元格的UICollectionViewController 类。当用户触摸一个单元格时,我想使用touchesBegan 方法来防止新的触摸,直到第一次触摸完成对单元格的选择。

我尝试将以下代码放在我的视图控制器中,但它从未被调用。

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
    super.touchesBegan(touches, withEvent: event)
    print("touches began")
}

但是,在我的项目的其他地方,我还有另一个类,它是UIViewController 的子类。在那里,我在以下代码中使用touchesBegan 来关闭该类中文本视图的键盘,并且该代码被正常调用。

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
    super.touchesBegan(touches, withEvent: event)
    view.endEditing(true)
}

为什么这段代码在一个类而不是另一个类中工作?以及如何在我的UICollectionViewController 中使用touchesBegan 来检测对我的集合视图单元格的触摸? Swift 中的解决方案将不胜感激。感谢您的宝贵时间!

研究: 我检查了这个解决方案: Handle Touch in UiCollectionView? 但答案大多适用于该特定项目。

我尝试使用手势识别器运行self.collectionView?.userInteractionEnabled = false,但手势识别器不会针对selector.state == .Began 触发,仅针对.Ended。所以我不能用它来防止进一步的接触。

我也尝试使用UILongPressGestureRecognizer 来做同样的事情,但是该手势阻止了集合视图单元格侦听的默认点击手势,因此从未收到对单元格的常规点击,因此无法选择单元格.

我发布了一个解决方法作为答案,尽管它没有回答原始问题。

【问题讨论】:

  • 我怀疑您的一个单元格可能没有将修饰转发到响应者链。如果您有自定义集合视图单元格,请确保它们正在调用 super.touchesBegan...
  • 我不知道为什么它没有调用(我认为圣诞老人在正确的道路上),但你能不能有一个 var hasBeenTouched : Bool 变量,在第一个之后设置为 true代码运行?然后要运行的代码全部放在if hasBeenTouched == false 块中。
  • @Tim - 我确实尝试过这个想法。在collectionView(:didSelectItemAtIndexPath) 中,如果hasBeenTouched == false 我将其设置为true,则禁用用户交互,并运行一个块来处理单元格选择。在块的末尾,我将 hasBeenTouched 设置为 false 并启用用户交互。但是由于某种原因,仍然有可能同时选择 2 个单元格,这会导致单元格选择功能“锁定”。我真的不明白为什么这种方法不起作用。
  • @SantaClaus - 我确实有自定义集合视图单元格。要为单元格调用super.touchesBegan,我会在我的UICollectionViewController 子类的collectionView:cellForItemAtIndexPath: 方法中进行调用吗?
  • 您是否阅读过文档 [这里?][1] [1]:developer.apple.com/library/ios/documentation/UIKit/Reference/…:您必须重写所有方法或不重写。也许这就是你的两个控制器的区别。

标签: ios swift uicollectionview touchesbegan uicollectionviewdelegate


【解决方案1】:

这是一种解决方法,但我没有使用touchesBegan,而是使用UICollectionViewDelegate 协议,这可以让我在UICollectionView 中选择一个单元格。

// The specified item should be selected.
override func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool {
    return true
}

override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    colorIndex = (indexPath as NSIndexPath).item // sets color index to the selected cell's path
    let selectedCell = collectionView.cellForItem(at: indexPath) as UICollectionViewCell!
print("Cell selected: \(selectedCell)")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-12
    相关资源
    最近更新 更多