Как сделать 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") } }
Вы пытались установить userInteractionEnabled
на true
на этикетке tripDetails
? Это должно сработать.
Обновление 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) } @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") }
Обновление Swift 3
yourLabel.isUserInteractionEnabled = true
Вам нужно включить взаимодействие пользователя с этим ярлыком …..
Например, для
yourLabel.userInteractionEnabled = true
Для swift 3.0 Вы также можете изменить длительность продолжительности нажатия жестов
label.isUserInteractionEnabled = true let longPress:UILongPressGestureRecognizer = UILongPressGestureRecognizer.init(target: self, action: #selector(userDragged(gesture:))) longPress.minimumPressDuration = 0.2 label.addGestureRecognizer(longPress)
Хорошее и удобное решение:
В вашем 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, with event: UIEvent?) { onClick() } }
В Storyboard выберите Label и на правой панели в «Identity Inspector» в полевом classе выберите LabelButton.
Не забудьте включить в Label Attribute Inspector «User Interaction Enabled»
Как описано в вышеприведенном решении, вы должны сначала включить взаимодействие с пользователем и добавить жестов кран
этот код был протестирован с использованием
Swift4 – Xcode 9.2
yourlabel.isUserInteractionEnabled = true yourlabel.addGestureRecognizer(UITapGestureRecognizer(){ //TODO })