可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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 })