【问题标题】:How could I ensure UITapGesture also triggers when a UIButton is tapped?当点击 UIButton 时,如何确保 UITapGesture 也会触发?
【发布时间】:2020-04-30 15:36:33
【问题描述】:

我有一个 UIViewController,它有 4 个 UICollectionView。每个 CollectionView 通过其 NIB 使用相同的自定义单元格。每个单元格上都有按钮,其操作是使用委托结构定义的。

在我的主视图控制器中,我实现了 UITapGesture 来获取屏幕上点击的坐标。但是,当按钮被点击时,UITapGesture 无法记录坐标(可能是因为它不是响应者)。

我想知道是否有方法可以获取按钮相对于主视图的屏幕坐标。

我尝试覆盖 touchBegan 但也失败了。

有什么方法可以让委托按钮触发多个操作? IE。是否触发了它的功能,同时还记录了水龙头的屏幕位置?

【问题讨论】:

    标签: ios swift uitapgesturerecognizer


    【解决方案1】:

    你不需要 UITapGesture:

    cellForItemAt 上,将唯一标识符存储为变量内的字符串。您还可以设置 IndexPath(但您有多个 CollectionViews),或者您可以为您的 UIButton 设置唯一标签。

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: MyCell.identifier, for: indexPath) as! MyCell
        cell.buttonIdentifier = "Cell-XY"
    }
    
    // Delegate
    func didTapOnMyButton(with identifier: String) {
        switch identifier {
        case "Cell-XY": // is button "Cell-XY"
        default: // can'z happend, but handle that too
        }
    }
    
    
    
    class MyCell: UICollectionViewCell {
        static let identifier = "MyCell"
    
        var buttonIdentifier = ""
    
        @objc didTapOnMyButton() {
            delegate?.didTapOnMyButton(with: buttonIdentifier)
        }
    
    
        override func prepareForReuse() {
            super.prepareForReuse()
            buttonIdentifier = ""
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-03
      • 2018-04-18
      • 1970-01-01
      相关资源
      最近更新 更多