NelbeDG
NelbeDG

Reputation: 445

How can I make a clickable UILabel in Swift 3?

I'm trying to make a clickable UILabel by following this code:

class ViewNotificationsDetails: UIViewController {    
   @IBOutlet weak var back: UILabel!

      override func viewDidLoad() {
          super.viewDidLoad()

          let tap = UITapGestureRecognizer(target: self, action: #selector(ViewNotificationsDetails.tapFunction))
          back.isUserInteractionEnabled = true
          back.addGestureRecognizer(tap)
      }

      @objc func tapFunction(sender:UITapGestureRecognizer) {
          print("tap working")
      } 
}

But when executing the code, I get the error ->

Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value on the line "back.isUserInteractionEnabled = true".

What could be the problem?

Upvotes: 2

Views: 3326

Answers (4)

vilas deshmukh
vilas deshmukh

Reputation: 399

If you are trying to achieve using storyboard, here is a simple way.

Add a UIButton element on the label. clear button placeholder, make button constraints equal to the label i.e equal height, equal width, Top, bottom. In the above image, label has only trailing fixed as it expands wrt text. so button trailing should be to trailing to the label. No leading constraint to the button in the below context. Finally created an IBAction and write your code to get your task done.

Upvotes: 0

Krunal
Krunal

Reputation: 79776

Problem is with your Label memory allocation. You have created IBOutlet of label but not connected it with Interface from your Storyboard/XIB view controller.

Go to your Interface Builder: (Storyboard/XIB) View Controller ▶ Select 'Connection Inspector' ▶ Connect label outlet 'back' with Label interface element

enter image description here

Upvotes: 0

Ahmad Taalab
Ahmad Taalab

Reputation: 215

try this code, is working well with me

class ViewController: UIViewController {
@IBOutlet weak var cliclableLable: UILabel!

override func viewDidLoad() {
    super.viewDidLoad()

    let tap = UITapGestureRecognizer(target: self, action: #selector(ViewController.tapFunction))
    cliclableLable.isUserInteractionEnabled = true
    cliclableLable.addGestureRecognizer(tap)
}

func tapFunction(sender:UITapGestureRecognizer) {
    print("tap working")
}

}

also don't forget to link your label with the code

Upvotes: 2

Syed Sadrul Ullah Sahad
Syed Sadrul Ullah Sahad

Reputation: 1312

Use back.userInteractionEnabled = true you did wrong as isUserInteractionEnabled.

Upvotes: 0

Related Questions