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

Как заставить UILabel реагировать на нажатие?

Я обнаружил, что я могу создать UILabel намного быстрее, чем UITextField, и я планирую использовать UILabel большую часть времени для своего приложения для отображения данных.

Короче говоря, я хочу, чтобы пользователь нажал на UILabel и ответил на мой ответ. Возможно ли это?

Спасибо.

4b9b3361

Ответ 1

Вы можете добавить экземпляр UITapGestureRecognizer в свой UILabel.

Например:

UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(labelTapped)];
tapGestureRecognizer.numberOfTapsRequired = 1;
[myLabel addGestureRecognizer:tapGestureRecognizer];
myLabel.userInteractionEnabled = YES;

Ответ 2

Если вы используете раскадровки, вы можете сделать весь этот процесс в раскадровке без дополнительного кода. Добавьте ярлык в раскадровку, а затем добавьте жук к ярлыку. В области "Утилиты" убедитесь, что для метки отмечен флажок "Взаимодействие с пользователем". С жестом tap (внизу вашего контроллера просмотра в раскадровке), ctrl + click и перетащите в файл ViewController.h и создайте Action. Затем выполните действие в файле ViewController.m.

Ответ 3

Swift 2.0:

Я добавляю строку nsmutable в качестве текста sampleLabel, позволяя пользователю взаимодействовать, добавляя жест нажатия и запуская метод.

override func viewDidLoad() {
    super.viewDidLoad()

    let newsString: NSMutableAttributedString = NSMutableAttributedString(string: "Tap here to read the latest Football News.")
    newsString.addAttributes([NSUnderlineStyleAttributeName: NSUnderlineStyle.StyleDouble.rawValue], range: NSMakeRange(4, 4))
    sampleLabel.attributedText = newsString.copy() as? NSAttributedString

    let tapGesture: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "tapResponse:")
    tapGesture.numberOfTapsRequired = 1
    sampleLabel.userInteractionEnabled =  true
    sampleLabel.addGestureRecognizer(tapGesture)

}
func tapResponse(recognizer: UITapGestureRecognizer) {
    print("tap")
}

Ответ 4

Вместо этого вы можете использовать UIButton и задавать текст так, как хотите. Кнопка не должна выглядеть как кнопка, если вы не хотите

Ответ 5

Swift 3.0

Инициализировать жест для tempLabel

tempLabel?.text = detailsModel.displayName
let tapAction = UITapGestureRecognizer(target: self, action: #selector(self.actionTapped(_:)))
tempLabel?.isUserInteractionEnabled = true
tempLabel?.addGestureRecognizer(tapAction)

Экстренный приемник

func actionTapped(_ sender: UITapGestureRecognizer) {
    // code here
}

Ответ 6

Если вы хотите использовать многострочный текст в своей кнопке, создайте UILabel с многострочным текстом и добавьте в качестве поднабора в свою кнопку.

например:

yourLabel=[Uilabel alloc]init];
yourLabel.frame=yourButtom.Frame;//(frame size should be equal to your button frame)
[yourButton addSubView:yourLabel]

Ответ 7

Чтобы добавить жестов Tap на UILable

UITapGestureRecognizer *tapAction = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(lblClick:)];
tapAction.delegate =self;
tapAction.numberOfTapsRequired = 1;

//Enable the lable UserIntraction
lblAction.userInteractionEnabled = YES;
[lblAction addGestureRecognizer:tapAction];   

и оценить селекторный метод

- (void)lblClick:(UITapGestureRecognizer *)tapGesture {

}

Примечание: добавьте UIGestureRecognizerDelegate в файл .h

Ответ 8

Быстрая версия: var tapGesture : UITapGestureRecognizer = UITapGestureRecognizer()

Затем внутри viewDidLoad() добавьте это:

  let yourLbl=UILabel(frame: CGRectMake(x,y,width,height)) as UILabel!

    yourLbl.text = "SignUp"
    tapGesture.numberOfTapsRequired = 1
    yourLbl.addGestureRecognizer(tapGesture)
    yourLbl.userInteractionEnabled = true
    tapGesture.addTarget(self, action: "yourLblTapped:")

Ответ 9

Свифт 3 из Элвина Джорджа

override func viewDidLoad() {
    super.viewDidLoad()
    let newsString: NSMutableAttributedString = NSMutableAttributedString(string: "Tap here to read the latest Football News.")
    newsString.addAttributes([NSUnderlineStyleAttributeName: NSUnderlineStyle.styleDouble.rawValue], range: NSMakeRange(4, 4))
    sampleLabel.attributedText = newsString.copy() as? NSAttributedString

    let tapGesture: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(ViewController.tapResponse))
    tapGesture.numberOfTapsRequired = 1
    sampleLabel.isUserInteractionEnabled =  true
    sampleLabel.addGestureRecognizer(tapGesture)
}

func tapResponse(recognizer: UITapGestureRecognizer) {
    print("tap")
}

Ответ 10

Быстрая версия выглядит так:

func addGestureRecognizerLabel(){
    //Create a instance, in this case I used UITapGestureRecognizer,
    //in the docs you can see all kinds of gestures
    let gestureRecognizer = UITapGestureRecognizer()

    //Gesture configuration
    gestureRecognizer.numberOfTapsRequired = 1
    gestureRecognizer.numberOfTouchesRequired = 1
    /*Add the target (You can use UITapGestureRecognizer init() for this)
    This method receives two arguments, a target(in this case is my ViewController) 
    and the callback, or function that you want to invoke when the user tap it view)*/
    gestureRecognizer.addTarget(self, action: "showDatePicker")

    //Add this gesture to your view, and "turn on" user interaction
    dateLabel.addGestureRecognizer(gestureRecognizer)
    dateLabel.userInteractionEnabled = true
}

//How you can see, this function is my "callback"
func showDatePicker(){
    //Your code here
    print("Hi, was clicked")
}

//To end just invoke to addGestureRecognizerLabel() when
//your viewDidLoad() method is called

override func viewDidLoad() {
    super.viewDidLoad()
    addGestureRecognizerLabel()
}