Search code examples
iosswiftuilabeluitapgesturerecognizerswift-playground

Swift Playground in Xcode - TapGestureRecognizer to UILabel not working


I am creating a Swift Playground in Xcode and I have a problem with putting a TapGestureRecognizer to an UILabel...

class MyViewController : UIViewController {

  override func loadView() {

    func tapped() {

        print("The label was tapped!")

    }

    let label11 = UILabel()
    label11.frame = CGRect(x: -350, y: 360, width: 350, height: 20)
    label11.text = "name."
    label11.textColor = .black
    label11.isUserInteractionEnabled = true
    view.addSubview(label11)

    let tap = UITapGestureRecognizer(target: self, action: "tapped")
    label11.addGestureRecognizer(tap)
  }
}

Solution

  • It appears that you're creating the view controller programmatically since you're operating solely in loadView (where you correctly did not call super), which requires you to create the actual view of that controller.

    import UIKit
    import PlaygroundSupport
    
    class MyViewController: UIViewController {
    
        override func loadView() {
    
            view = UIView()
    
            let label11 = UILabel()
            label11.frame = CGRect(x: 0, y: 360, width: 350, height: 20)
            label11.text = "name."
            label11.textColor = .yellow
            label11.isUserInteractionEnabled = true
            view.addSubview(label11)
    
            let tap = UITapGestureRecognizer(target: self, action: #selector(tapped))
            label11.addGestureRecognizer(tap)
    
        }
    
        @objc func tapped() {
            print("The label was tapped!")
        }
    
    }
    
    PlaygroundPage.current.liveView = MyViewController()
    

    Alternatively, you can replicate a non-programmatic view controller by using viewDidLoad (which requires you to call super).

    import UIKit
    import PlaygroundSupport
    
    class MyViewController: UIViewController {
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            let label11 = UILabel()
            label11.frame = CGRect(x: 0, y: 360, width: 350, height: 20)
            label11.text = "name."
            label11.textColor = .yellow
            label11.isUserInteractionEnabled = true
            view.addSubview(label11)
    
            let tap = UITapGestureRecognizer(target: self, action: #selector(tapped))
            label11.addGestureRecognizer(tap)
    
        }
    
        @objc func tapped() {
            print("The label was tapped!")
        }
    
    }
    
    PlaygroundPage.current.liveView = MyViewController()
    

    Also, your origin-x value was out of bounds which is why you may not have seen the label and you were missing @objc syntax which is required in Swift 4.