【问题标题】:Swift - Multiple UILabel click events to same functionSwift - 多个 UILabel 点击事件到相同的功能
【发布时间】:2018-04-25 11:57:53
【问题描述】:

我需要在多个UILabel中添加一个UITapGestureRecognizer,它们都需要去同一个函数进行处理。

我拥有的是这样的:

@IBOutlet weak var label_something: UILabel!
let tap = UITapGestureRecognizer(target: self, action: #selector(self.myFunction))
label_something.addGestureRecognizer(tap)

在这里收到:

@objc func myFunction(sender:UITapGestureRecognizer) { // Something... }

像魅力一样工作。问题是它只适用于一个 UILabel(如果将 addGestureRecognizer(tap) 添加到多个 UIlabel 它只适用于添加的最后一个)

所以我的问题是:

如何在这里实现我想要做的?五个不同的 UILabel 和 tapRecognizer 去同一个函数

【问题讨论】:

  • 你是如何确定myFunction(sender:) 只为一个标签调用的?如果您点击另一个标签,它没有调用。你检查过日志吗?
  • 是的,函数中的简单 print("hepp") 仅在单击有效的那个时才会显示。
  • 您能在这里看到更多代码吗?即你如何分配label_something
  • 你为什么使用标签而不是按钮?
  • @Sourcey86 你在哪里为所有其他标签添加了手势?

标签: swift uilabel uitapgesturerecognizer


【解决方案1】:

UIGestureRecognizer 与单个视图一起使用,您必须创建UIGestureRecognizer 的新实例

func setGesture() -> UITapGestureRecognizer {

     var myRecognizer = UITapGestureRecognizer()

     myRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.myFunction))
     return myRecognizer
}

label_something1.addGestureRecognizer(setGesture())    
label_something2.addGestureRecognizer(setGesture())

【讨论】:

    【解决方案2】:

    如果您从 UITapGestureRecognizer 添加新实例,它将正常工作,例如

    let tap = UITapGestureRecognizer(target: self, action: #selector(self.myFunction))
    label_1.addGestureRecognizer(tap)
    let tap2 = UITapGestureRecognizer(target: self, action: #selector(self.myFunction))
    label_2.addGestureRecognizer(tap)
    

    【讨论】:

    • 您确定需要为每个标签创建新手势吗?
    • @Mani 手势识别器只能附加到一个视图。原因是每个识别器都可以有自己的手势状态(一个被触发,另一个未被触动)。
    • 我认为是的,因为如果你使用相同的实例,它将被添加到最后一个标签。
    • @Crazyrems 你明白了。看到这个之后。 stackoverflow.com/questions/4747238/…
    • @Mani 是的。每个标签都需要一个点击手势识别器,即一个UITapGestureRecognizer只能分配给单个组件,这就是为什么last标签识别tap,它会自动从以前的标签中删除。但是,所有手势都可以有相同的选择器方法。
    【解决方案3】:

    每个 UIView 都需要自己的识别器,对于这种情况,我有一个小助手功能。随意复制/粘贴。

    private func addTapRecognizer(toView view: UIView) {
            let recognizer = UITapGestureRecognizer(target: self, action: #selector(didTapButton(sender:)))
            view.isUserInteractionEnabled = true
            view.addGestureRecognizer(recognizer)
        }
    
        @objc private func didTapButton(sender: UIGestureRecognizer) {
            guard let view = sender.view else {
                return
            }
    
            switch view {
            case self.imageView: // any view you want to check
            default:
                print(sender.debugDescription)
            }
         }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-10-26
      • 1970-01-01
      • 1970-01-01
      • 2013-04-14
      • 1970-01-01
      • 1970-01-01
      • 2023-03-19
      相关资源
      最近更新 更多