【问题标题】:Adding a gesture to a label?向标签添加手势?
【发布时间】:2018-09-25 08:58:27
【问题描述】:

Swift 4 iOS 11

尝试使用此代码向标签添加手势,它会触发,但会因无法识别的选择器而崩溃。

尝试使用和不使用@objc,也尝试使用@selector(ViewController.copyURL),尝试打开isUserInteractiveEnabled = true;没有工作

@IBOutlet weak var zeroURL: UILabel!

let press = UILongPressGestureRecognizer(target: zeroURL, action: #selector(copyURL))
view.addGestureRecognizer(press)

@objc func copyURL() {
    UIPasteboard.general.string = self.zeroURL.text
    print("copied")
    zeroURL.alpha = 0
    UIView.animate(withDuration: 0.75, delay: 0.25, options: [.curveEaseOut], animations: {
        self.zeroURL.alpha = 1.0
    }) { (status) in
        // do nothing
    }
}

【问题讨论】:

  • 你的zeroURL是什么?

标签: ios swift uilabel uigesturerecognizer unrecognized-selector


【解决方案1】:

目标应该是自己,你需要将手势识别器添加到标签,而不是视图

let press = UILongPressGestureRecognizer(target: self, action: #selector(copyURL))
zeroURL.addGestureRecognizer(press)

在这里的第一行,您正在配置手势识别器,告诉它self.copyURL 是识别该手势时要使用的目标操作。第二行将手势添加到UILabel

【讨论】:

    【解决方案2】:

    替换这个

    let press = UILongPressGestureRecognizer(target: zeroURL, action: #selector(copyURL))
    view.addGestureRecognizer(press)
    

    let press = UILongPressGestureRecognizer(target: self, action: #selector(copyURL))
    zeroURL.addGestureRecognizer(press)
    

    作为目标应该包含选择器方法的实现

    【讨论】:

      【解决方案3】:

      将目标设为self 而不是zeroURL,如下所示:

      let press = UILongPressGestureRecognizer(target: self, action:#selector(copyURL))
      zeroURL.addGestureRecognizer(press)
      
      @objc func copyURL() {
          UIPasteboard.general.string = self.zeroURL.text
          print("copied")
          zeroURL.alpha = 0
          UIView.animate(withDuration: 0.75, delay: 0.25, options: [.curveEaseOut], animations: {
          self.zeroURL.alpha = 1.0
          }) { (status) in
              // do nothing
          }
      }
      

      编辑:在您的UILabel 上添加长按手势,但不在您的view 上,如下所示:

      zeroURL.addGestureRecognizer(press)
      

      【讨论】:

      • 是的,这解决了它......但我现在到处长按。我只想长按 zeroURL。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-09-08
      • 1970-01-01
      • 1970-01-01
      • 2012-08-17
      • 1970-01-01
      • 1970-01-01
      • 2021-07-08
      相关资源
      最近更新 更多