Swift:如何使UILabel可点击?

我想做一个UILabel点击。

我试过这个,但是不起作用:

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") } } 

你有没有尝试在tripDetails标签上设置userInteractionEnabledtrue ? 这应该工作。

Swift 3更新

更换

 Selector("tapFunction:") 

 #selector(DetailViewController.tapFunction) 

例:

 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") } } 

Swift 3更新

 yourLabel.isUserInteractionEnabled = true 

您需要启用该标签的用户交互…..

例如

yourLabel.userInteractionEnabled = true

SWIFT 4.0更新

  @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") } 

对于SWIFT 3.0,你也可以改变手势长按持续时间

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