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?
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
使用back.userInteractionEnabled = true
你做错了 isUserInteractionEnabled。
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
Add a UIButton element on the label. clear button placeholder, make button constraints equal to the label ie 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.