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")
}
}
답변
라벨 에 설정 isUserInteractionEnabled
을 시도 했습니까 ? 이 작동합니다.true
tripDetails
답변
스위프트 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)
}
@objc
func tapFunction(sender:UITapGestureRecognizer) {
print("tap working")
}
}
답변
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")
}
답변
스위프트 3 업데이트
yourLabel.isUserInteractionEnabled = true
답변
스위프트 5
@liorco 와 비슷 하지만 @objc 를 @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")
}
}
이것은 Xcode 10.2에서 작동합니다.
답변
좋고 편리한 솔루션 :
ViewController에서 :
@IBOutlet weak var label: LabelButton!
override func viewDidLoad() {
super.viewDidLoad()
self.label.onClick = {
// TODO
}
}
이것을 ViewController 또는 다른 .swift 파일 (예 : CustomView.swift)에 배치 할 수 있습니다.
@IBDesignable class LabelButton: UILabel {
var onClick: () -> Void = {}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
onClick()
}
}
스토리 보드에서 레이블을 선택하고 필드 클래스의 “Identity Inspector”에있는 오른쪽 분할 창에서 LabelButton을 선택하십시오.
Label Attribute Inspector “User Interaction Enabled”에서 활성화하는 것을 잊지 마십시오
답변
해당 라벨의 사용자 상호 작용을 활성화해야합니다 …..
예를 들어
yourLabel.userInteractionEnabled = true
