Dan*_*e B 120 uilabel ios uitapgesturerecognizer swift
我想让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")
}
}
Run Code Online (Sandbox Code Playgroud)
小智 101
Swift 3更新
更换
Selector("tapFunction:")
Run Code Online (Sandbox Code Playgroud)
同
#selector(DetailViewController.tapFunction)
Run Code Online (Sandbox Code Playgroud)
例:
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)
}
@objc
func tapFunction(sender:UITapGestureRecognizer) {
print("tap working")
}
}
Run Code Online (Sandbox Code Playgroud)
Xco*_*ngi 43
SWIFT 4更新
@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")
}
Run Code Online (Sandbox Code Playgroud)
Ind*_*ada 14
Swift 3更新
yourLabel.isUserInteractionEnabled = true
Run Code Online (Sandbox Code Playgroud)
res*_*her 14
好用又方便的解决方法:
在您的 ViewController 中:
@IBOutlet weak var label: LabelButton!
override func viewDidLoad() {
super.viewDidLoad()
self.label.onClick = {
// TODO
}
}
Run Code Online (Sandbox Code Playgroud)
你可以把它放在你的 ViewController 或另一个 .swift 文件中(例如 CustomView.swift):
@IBDesignable class LabelButton: UILabel {
var onClick: () -> Void = {}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
onClick()
}
}
Run Code Online (Sandbox Code Playgroud)
在 Storyboard 中选择 Label,然后在字段类中的“Identity Inspector”的右侧窗格中选择 LabelButton。
不要忘记在标签属性检查器中启用“启用用户交互”
迅捷5
Similar to @liorco, but need to replace @objc with @IBAction.
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)
}
@IBAction func tapFunction(sender: UITapGestureRecognizer) {
print("tap working")
}
}
Run Code Online (Sandbox Code Playgroud)
This is working on Xcode 10.2.
归档时间: |
|
查看次数: |
94168 次 |
最近记录: |