如何使UILabel响应点击?


94

我发现我创建UILabel的速度比UITextField快得多,并且我打算在大多数时间将UILabel用于数据显示应用程序。

长话短说,我希望用户点击UILabel并让我的回调对此做出响应。那可能吗?

谢谢。


1
您需要指定userInteractionEnabled = true
onmyway133

Answers:


208

您可以将UITapGestureRecognizer实例添加到UILabel。

例如:

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

13
啊哈,这里的“ userInteractionEnabled”属性是关键(因为其他配置可以并且最好在情节提要中进行设置)。Label的默认设置为关闭交互,以便通过它们进行触摸-但在这种情况下,他们需要观察触摸才能激活手势识别器。谢谢!
2016年

1
好一个!我只是在标签上轻敲一下,完全忘了启用用户交互功能。谢谢!
Mike Critchley

37

如果使用情节提要,则可以在情节提要中完成整个过程,而无需其他代码。在情节提要中添加标签,然后在标签上添加轻击手势。在“实用工具”窗格中,确保已选中“已启用用户交互”标签。通过轻击手势(在情节提要中的视图控制器底部),按住Ctrl键并单击并拖动到ViewController.h文件,然后创建一个Action。然后在ViewController.m文件中实现该动作。


方法也可以使用Interface Builder无需单独的故事板
Gomino

确保在“ 属性 ”检查器的“ 视图”部分下,而不只是在“辅助功能特征”下,选中“已启用用户交互” 。
SeanR

17

斯威夫特3.0

初始化手势 tempLabel

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

动作接收者

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

迅捷4.0

初始化手势 tempLabel

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

动作接收者

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

如何从发送方对象获取标签文本?换句话说,如何识别发件人?
Vineel

Swift 4版本具有@selector而不是#selector。
Kirby Todd

8

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并将文本设置为所需的文本。如果您不想,按钮不必看起来像按钮


1
关于这一点,我一直在UIButton左对齐多行文本方面遇到麻烦。即使我将左对齐设置为居中,它仍然会发生。
快乐

我确实尝试过UIButton,它非常不错。只是多行按钮是一个问题。谢谢。
快乐

3

在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 {

}

注意:在.h文件中添加UIGestureRecognizerDelegate


2

迅捷版: 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:")

1

如果要在按钮中使用多行文本,请使用多行文本创建一个UILabel,并将其作为子视图添加到按钮中。

例如:

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

1

来自Alvin George的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版本如下所示:

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

我个人更喜欢为UILabel编写扩展的方法。这就是我用的。

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()]?()
    }
}

然后,您可以在任何UILabel实例中使用它:

myLabel.setOnTapped {
    // do something
}

我相信,这可能会导致某些内存泄漏,但是我还没有确定如何最好地解决它们。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.