Home > Software design >  swift5 UILabel Clickable
swift5 UILabel Clickable

Time:09-16

I am learning iOS development. And I want to make UILabel clickable Here is what I have done but with no result.

@IBOutlet weak var coordinate: UILabel!
override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        coordinate.adjustsFontSizeToFitWidth = true
        
        let tap = UIGestureRecognizer(target: self, action: #selector(uiLabelClicked()))
        coordinate.addGestureRecognizer(tap)
        coordinate.isUserInteractionEnabled = true

Below is a function that is expected to perform an action when label is clicked.

 @objc func uiLabelClicked(){
            let alert = UIAlertController(title: "Coordinate", message: "I have been clicked...", preferredStyle: .alert)
            self.present(alert, animated: true, completion: nil)
            debugPrint("clicked")
            
        }

I apologize for my English I am using google translator.

CodePudding user response:

Try this:

@IBOutlet weak var coordinate: UILabel!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.
    coordinate.adjustsFontSizeToFitWidth = true

    let tap = UITapGestureRecognizer(target: self, action: #selector(self.labelAction(_:)))
    coordinate.addGestureRecognizer(tap)
    coordinate.isUserInteractionEnabled = true
}

@objc func labelAction(_ sender: UIGestureRecognizer) {
    let alert = UIAlertController(title: "Coordinate", message: "I have been clicked...", preferredStyle: .alert)
    self.present(alert, animated: true, completion: nil)
    debugPrint("clicked")
}
  • Related