UILabel'in dokunmaya yanıt vermesini nasıl sağlayabilirim?


94

UILabel'i UITextField'den çok daha hızlı oluşturabileceğimi keşfettim ve çoğu zaman UILabel'i veri görüntüleme uygulamam için kullanmayı planlıyorum.

Uzun lafın kısası olsa da, kullanıcının bir UILabel'e dokunmasına ve geri aramamın buna yanıt vermesine izin vermek istiyorum. Mümkün mü?

Teşekkürler.


2
Belirtmeniz gerekiyoruserInteractionEnabled = true
onmyway133

Yanıtlar:


211

UITapGestureRecognizerUILabel'inize bir örnek ekleyebilirsiniz .

Örneğin:

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

14
Aha, buradaki 'userInteractionEnabled' özelliği anahtardır (çünkü diğer yapılandırma film şeridinde ayarlanabilir ve tercihen ayarlanmalıdır). Etiket varsayılan olarak etkileşimi üzerlerindeki dokunuşlardan geçmek için kapalıdır - ancak bu durumda hareket tanıyıcının etkinleştirilmesi için dokunmaları gözlemlemeleri gerekir. Teşekkürler!
Marchy

1
Güzel bir! Sadece bir etikete dokunuyordum ve kullanıcı etkileşimini etkinleştirmeyi tamamen unuttum. Teşekkürler!
Mike Critchley

37

Film şeridi kullanıyorsanız, tüm bu işlemi film şeridinde ek kod olmadan yapabilirsiniz. Film şeridine bir etiket ekleyin, ardından etikete bir dokunma hareketi ekleyin. Yardımcı Programlar bölmesinde, etiket için "Kullanıcı Etkileşimi Etkin" seçeneğinin işaretli olduğundan emin olun. Dokunma hareketinden (film şeridindeki görünüm denetleyicinizin altında), ctrl + tıklayın ve ViewController.h dosyanıza sürükleyin ve bir Eylem oluşturun. Ardından eylemi ViewController.m dosyasında uygulayın.


Yöntem de mevcuttur storyboardlar olmadan yalnız arayüzü geliştirici ile
Gomino

Yalnızca Erişilebilirlik Özellikleri değil , Özellikler denetçisindeki Görünüm bölümünün altında "Kullanıcı Etkileşimi Etkin" seçeneğinin işaretlendiğinden emin olun .
SeanR

17

Swift 3.0

İçin hareketi başlat tempLabel

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

Eylem alıcısı

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

Swift 4.0

İçin hareketi başlat tempLabel

tempLabel?.text = "Label"
let tapAction = UITapGestureRecognizer(target: self, action:@selector(actionTapped(_:)))
tempLabel?.isUserInteractionEnabled = true
tempLabel?.addGestureRecognizer(tapAction)

Eylem alıcısı

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

Gönderen nesnesinden etiket metni nasıl alınır? Başka bir deyişle, gönderen nasıl belirlenir?
Vineel

Swift 4 sürümünde #selector yerine @selector bulunur.
Kirby Todd

8

Swift 2.0:

SampleLabel'in metni olarak bir nsmutable dizesi ekliyorum, kullanıcı etkileşimini etkinleştiriyorum, bir dokunma hareketi ekliyorum ve bir yöntemi tetikliyorum.

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

Bunun yerine bir UIButton kullanabilir ve metni istediğiniz şeye ayarlayabilirsiniz. İstemiyorsanız düğmenin düğme gibi görünmesi gerekmez.


1
Bununla ilgili olarak, çok satırlı metni sola yaslama UIButton ile her zaman sorun yaşadım. Sola hizalamayı merkeze ayarladığımda bile yine de oluyor.
mutlu

Yine de UIButton'a bir şans verdim ve oldukça güzel. Sorun olan sadece çok hatlı düğmelerdir. Teşekkürler.
mutlu

3

UILable'a Dokunma hareketi eklemek için

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];   

ve seçici yöntemi değerlendirmek için

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

}

Not: UIGestureRecognizerDelegate'i .h dosyasına ekleyin


2

Swift Versiyonu: var tapGesture : UITapGestureRecognizer = UITapGestureRecognizer()

Sonra içeriye şunu viewDidLoad()ekleyin:

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

1

UILabelDüğmenizde Çok satırlı metin kullanmak istiyorsanız, Çok satırlı metin içeren bir metin oluşturun ve düğmenize alt görünüm olarak ekleyin.

örneğin:

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

1

Alvin George'dan Swift 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")
}

0

Swift versiyonu şuna benzer:

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's 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()
}

0

Ben şahsen UILabel için bir uzantı yazma yöntemini tercih ediyorum. Kullandığım şey bu.

import UIKit

extension UILabel {
    /**
     * A map of actions, mapped as [ instanceIdentifier : action ].
     */
    private static var _tapHandlers = [String:(()->Void)]()

    /**
     * Retrieve the address for this UILabel as a String.
     */
    private func getAddressAsString() -> String {
        let addr = Unmanaged.passUnretained(self).toOpaque()
        return "\(addr)"
    }

    /**
     * Set the on tapped event for the label
     */
    func setOnTapped(_ handler: @escaping (()->Void)) {
        UILabel._tapHandlers[getAddressAsString()] = handler
        let gr = UITapGestureRecognizer(target: self, action: #selector(onTapped))
        gr.numberOfTapsRequired = 1
        self.addGestureRecognizer(gr)
        self.isUserInteractionEnabled = true
    }

    /**
     * Handle the tap event.
     */
    @objc private func onTapped() {
        UILabel._tapHandlers[self.getAddressAsString()]?()
    }
}

Daha sonra bunu herhangi bir UILabel örneğinden şu şekilde kullanırsınız:

myLabel.setOnTapped {
    // do something
}

Bu, inandığım bazı bellek sızıntılarına neden olabilir, ancak bunları en iyi nasıl çözeceğimi henüz belirlemedim.


0

Bu, Xcode 12 ve Swift 5'te harika çalışıyor

let tapAction = UITapGestureRecognizer(target: self,action:#selector(actionTapped(_:)))

userLabel?.isUserInteractionEnabled = true

userLabel?.addGestureRecognizer(tapAction)

Ve eylem yöntemi -

@objc func actionTapped(_ sender: UITapGestureRecognizer) {
        print("tapped")
    }
Sitemizi kullandığınızda şunları okuyup anladığınızı kabul etmiş olursunuz: Çerez Politikası ve Gizlilik Politikası.
Licensed under cc by-sa 3.0 with attribution required.