ios 如何让 UILabel 响应点击?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7154340/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 21:13:06  来源:igfitidea点击:

How to get UILabel to respond to tap?

iosipaduilabel

提问by Happy

I have discovered that I can create UILabel much faster than UITextField and I plan to use UILabel most of the time for my data display app.

我发现创建 UILabel 的速度比 UITextField 快得多,而且我计划大部分时间将 UILabel 用于我的数据显示应用程序。

To make a long story short though, I wish to let the user tap on a UILabel and have my callback respond to that. Is that possible?

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

Thanks.

谢谢。

回答by pythonquick

You can add a UITapGestureRecognizerinstance to your UILabel.

您可以UITapGestureRecognizer向 UILabel添加一个实例。

For example:

例如:

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

回答by leenyburger

If you're using storyboards you can do this entire process in the storyboard with no additional code. Add a label to the storyboard, then add a tap gesture to the label. In the Utilities pane, make sure "User Interaction Enabled" is checked for the label. From the tap gesture (at the bottom of your view controller in the storyboard), ctrl+click and drag to your ViewController.h file and create an Action. Then implement the action in the ViewController.m file.

如果您使用情节提要,则无需额外代码即可在情节提要中完成整个过程。向情节提要添加标签,然后向标签添加点击手势。在“实用工具”窗格中,确保为标签选中“启用用户交互”。从点击手势(在故事板中视图控制器的底部),按住 ctrl+单击并拖动到您的 ViewController.h 文件并创建一个动作。然后在 ViewController.m 文件中实现操作。

回答by Koushik

Swift 3.0

斯威夫特 3.0

Initialize the gesture for tempLabel

初始化手势 tempLabel

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

Action receiver

动作接收器

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

Swift 4.0

斯威夫特 4.0

Initialize the gesture for tempLabel

初始化手势 tempLabel

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

Action receiver

动作接收器

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

回答by A.G

Swift 2.0:

斯威夫特 2.0:

I am adding a nsmutable string as sampleLabel's text, enabling user interaction, adding a tap gesture and trigger a method.

我正在添加一个 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")
}

回答by Matt S.

You could use a UIButton instead and set the text to what you want. The button doesn't have to look like a button if you don't want to

您可以改用 UIButton 并将文本设置为您想要的。如果您不想,按钮不必看起来像按钮

回答by Hardik Thakkar

To add Tap gesture on UILable

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

and to assess the selector method

并评估选择器方法

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

}

Note: Add UIGestureRecognizerDelegate in .h file

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

回答by Aditya Jha

Swift Version:var tapGesture : UITapGestureRecognizer = UITapGestureRecognizer()

迅捷版:var tapGesture : UITapGestureRecognizer = UITapGestureRecognizer()

Then inside viewDidLoad(),add this:

然后在里面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:")

回答by MRustamzade

Swift 3 from Alvin George

来自阿尔文乔治的斯威夫特 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")
}

回答by Chandramani

If you want to use Multi line text in your button then create a UILabelwith Multiline text and add as a subview in to your button.

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

for eg:

例如:

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

回答by LeoGalante

Swift version looks like this:

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