ios - CollectionViewCell 中的 UILabel 不阻止触摸事件

标签 ios swift cocoa-touch uikit

我有什么

  • A 是一个UICollectionView
  • B 是一个 UICollectionViewCell
  • C 是 B 的 UILabel subview

    +------------------------------+
    |A                             |
    |                              |
    | +----------+    +----------+ |
    | |C         |    |B         | |
    | |----------|    |          | |
    | |          |    |          | |
    | |B         |    |          | |
    | +----------+    +----------+ |
    +------------------------------+
    

当点击 B 时,C 作为 subview 添加到单元格的顶部。当再次点击 B 时,C 将从父 View (B) 中移除。

问题

触摸事件从 C 到 B。

我似乎找不到如何忽略/阻止这些触摸事件;即,点击 UILabel C 不应传播到响应链。

例如,如果 C 是一个 UIButton、一个 UICollectionView 等,它会自动“拦截”触摸事件。为何如此?它们都继承自 UIResponder 作为 UIView...

最佳答案

默认情况下,UILabel 没有用户交互 - 因此它不会“拦截”触摸。

如果您在 C 标签上设置 .isUserInteractionEnabled = true,它应该“吃掉”触摸。

编辑:使用实际 Collection View 单元格快速测试后...您还需要向标签添加手势识别器以“吃掉”触摸。在我的(新的,改进的)快速测试中,对标签进行子类化对我有用:

class EatTouchesLabel: UILabel {

    var myGest: UIGestureRecognizer!

    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)!
        self.commonInit()
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        self.commonInit()
    }

    func commonInit() {
        self.isUserInteractionEnabled = true
        if myGest == nil {
            myGest = UITapGestureRecognizer()
            self.addGestureRecognizer(myGest)
        }
    }

}

关于ios - CollectionViewCell 中的 UILabel 不阻止触摸事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44055663/

相关文章:

ios - NSUserDefaults 不递增

ios - iAds : Displaying own ads when didFailToReceiveAdWithError

c++ - Cocos2dx 2.2.3 架构 arm64::WebPInitDecoderConfigInternal 的 undefined symbol

ios - Storyboard 中单个 UITableView 内的 10 个单元格(2 行,5 列)的网格

iphone - 有没有办法在 Xcode 的 resources 文件夹中创建子文件夹?

ios - 使用自动布局将自定义 UIView 垂直和水平居中

iphone - 多选 TableView 单元格且无选择样式

javascript - 为什么我收到 "Element type is invalid"错误?

SWIFT - 从 Mapkit 获取县信息

java - 为什么 Swift 不隐式地为每个类提供 hashable?