How to make a UILabel clickable?

匿名 (未验证) 提交于 2019-12-03 03:06:01

问题:

I would like to make a UILabel clickable.

I have tried this, but it doesn't work:

class DetailViewController: UIViewController {      @IBOutlet weak var tripDetails: UILabel!      override func viewDidLoad() {         super.viewDidLoad()         ...         let tap = UITapGestureRecognizer(target: self, action: Selector("tapFunction:"))         tripDetails.addGestureRecognizer(tap)     }      func tapFunction(sender:UITapGestureRecognizer) {         print("tap working")     } }

回答1:

Have you tried to set userInteractionEnabled to true on the tripDetails label? This should work.



回答2:

Swift 3 Update

Replace

Selector("tapFunction:")

with

#selector(DetailViewController.tapFunction)

Example:

class DetailViewController: UIViewController {      @IBOutlet weak var tripDetails: UILabel!      override func viewDidLoad() {         super.viewDidLoad()         ...          let tap = UITapGestureRecognizer(target: self, action: #selector(DetailViewController.tapFunction))         tripDetails.isUserInteractionEnabled = true         tripDetails.addGestureRecognizer(tap)     }      func tapFunction(sender:UITapGestureRecognizer) {         print("tap working")     } }


回答3:

SWIFT 4 Update

 @IBOutlet weak var tripDetails: UILabel!   override func viewDidLoad() {     super.viewDidLoad()      let tap = UITapGestureRecognizer(target: self, action: #selector(GameViewController.tapFunction))     tripDetails.isUserInteractionEnabled = true     tripDetails.addGestureRecognizer(tap) }  @objc func tapFunction(sender:UITapGestureRecognizer) {      print("tap working") }


回答4:

Swift 3 Update

yourLabel.isUserInteractionEnabled = true


回答5:

You need to enable the user interaction of that label.....

For e.g

yourLabel.userInteractionEnabled = true



回答6:

For swift 3.0 You can also change gesture long press time duration

label.isUserInteractionEnabled = true let longPress:UILongPressGestureRecognizer = UILongPressGestureRecognizer.init(target: self, action: #selector(userDragged(gesture:)))  longPress.minimumPressDuration = 0.2 label.addGestureRecognizer(longPress)


回答7:

As described in the above solution you should enable the user interaction first and add the tap gesture

this code has been tested using

Swift4 - Xcode 9.2

yourlabel.isUserInteractionEnabled = true yourlabel.addGestureRecognizer(UITapGestureRecognizer(){                 //TODO              })


转载请标明出处:How to make a UILabel clickable?
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!