Search code examples
iosswift4swift4.2

Swift 4 - UITapGestureRecognizer selector function not calling


Im trying to add a "click event" to a label rather that a button. Im not using storyboard.

[...]

let registerLabel: UILabel = {
    let label = UILabel()
    let tapGesture = UITapGestureRecognizer(target: self, action: #selector(openLoginView))
    tapGesture.numberOfTapsRequired = 1
    label.translatesAutoresizingMaskIntoConstraints = false
    label.text = "Register"
    label.isUserInteractionEnabled = true
    label.addGestureRecognizer(tapGesture)
    label.textColor = Colors.lightGrey
    label.font = label.font.withSize(18)
    return label
}()

[...] // viewDidLoad()

@objc private func openLoginView(sender: UITapGestureRecognizer) {
    print("PRINT ME-->>>>>>>>>")
}

[...]

In the iPhone 6s simulator, nothing is printing inside of the console when I use the mouse to simulate a tap with a mouse click. Am I missing something?


Solution

  • You need to make your registerLabel declared lazily. Like so:

    lazy var registerLabel: UILabel = {
        let label = UILabel(frame: CGRect(x: 200, y: 300, width: 200, height: 50))
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(openLoginView(sender:)))
        tapGesture.numberOfTapsRequired = 1
        label.translatesAutoresizingMaskIntoConstraints = false
        label.text = "Register"
        label.isUserInteractionEnabled = true
        label.addGestureRecognizer(tapGesture)
        label.textColor = .black
        label.font = label.font.withSize(18)
        return label
    }()
    

    Also, take a look at my selector if you need to do something with the sender in your openLoginView function.

    More info about Lazy Stored Properties

    A lazy stored property is a property whose initial value is not calculated until the first time it is used. You indicate a lazy stored property by writing the lazy modifier before its declaration.

    https://docs.swift.org/swift-book/LanguageGuide/Properties.html

    I hope this helps! :)