添加到UILabel的点击手势识别器无法正常工作

时间:2017-01-20 21:41:05

标签: ios swift

我使用以下代码将手势识别器添加到UILabel。勾选故事板中标签的用户交互已启用,但是当我点击标签时,未调用onUserClickingSendToken方法。

class ViewController: UIViewController, MFMailComposeViewControllerDelegate {

    @IBOutlet weak var tokenDisplay: UILabel!
    var tapGestureRecognizer:UITapGestureRecognizer = UITapGestureRecognizer(target:self, action:  #selector(onUserClickingSendToken(_:)))

    override func viewDidLoad() {
        super.viewDidLoad()
        tapGestureRecognizer.numberOfTapsRequired = 1
        tokenDisplay.addGestureRecognizer(tapGestureRecognizer)
    }

    func onUserClickingSendToken(_ sender: Any)
    {
      ....

2 个答案:

答案 0 :(得分:5)

在viewDidLoad中初始化tapRecognizer应该这样做,因为您在初始化视图之前将自己定位为self

class ViewController: UIViewController, MFMailComposeViewControllerDelegate {

@IBOutlet weak var tokenDisplay: UILabel!
var tapGestureRecognizer:UITapGestureRecognizer!

override func viewDidLoad() {
    super.viewDidLoad()
    tapGestureRecognizer = UITapGestureRecognizer(target:self, action:      #selector(onUserClickingSendToken(_:)))
    tapGestureRecognizer.numberOfTapsRequired = 1
    tokenDisplay.isUserInteractionEnabled = true
    tokenDisplay.addGestureRecognizer(tapGestureRecognizer)
}

func onUserClickingSendToken(_ sender: Any)
{
  ....

答案 1 :(得分:0)

尝试将选择器设置更改为:

#selector(ViewController .onUserClickingSendToken(_:)