Подтвердить что ты не робот

Как сделать 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")
    }
}
4b9b3361

Ответ 1

Вы пытались установить для isUserInteractionEnabled значение true на tripDetails? Это должно работать.

Ответ 2

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

Ответ 3

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

Ответ 4

Обновление Swift 3

yourLabel.isUserInteractionEnabled = true

Ответ 5

Swift 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.

Ответ 6

Вам нужно включить взаимодействие пользователя с этой меткой.....

Например,

yourLabel.userInteractionEnabled = true

Ответ 7

Хорошее и удобное решение:

В вашем 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()
    }
}

В раскадровке выберите "Метка", а в правой части окна "Инспектор идентификации" в классе поля выберите "LabelButton".

Не забудьте включить в Инспекторе атрибутов метки "Взаимодействие с пользователем включено"

Ответ 8

Для swift 3.0 Вы также можете изменить длительность продолжительности продолжительности жестов

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

Ответ 9

Довольно легко пропустить, как я, но не забудьте использовать UITapGestureRecognizer, а не UIGestureRecognizer.

Ответ 10

Как описано в приведенном выше решении, вы должны сначала включить взаимодействие с пользователем и добавить жест касания.

этот код был протестирован с использованием

Swift4 - Xcode 9.2

yourlabel.isUserInteractionEnabled = true
yourlabel.addGestureRecognizer(UITapGestureRecognizer(){
                //TODO 
            })