如何使UILabel响应点击?

101

我发现创建UILabel比UITextField快得多,计划在我的数据展示应用中大部分时间使用UILabel。

简而言之,我希望允许用户点击UILabel并在我的回调函数中响应。这是否可能?

谢谢。


4
请将 userInteractionEnabled = true 翻译为“需要设置'用户交互使能'为真”。 - onmyway133
12个回答

220
你可以向UILabel添加一个UITapGestureRecognizer实例。
例如:
UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(labelTapped)];
tapGestureRecognizer.numberOfTapsRequired = 1;
[myLabel addGestureRecognizer:tapGestureRecognizer];
myLabel.userInteractionEnabled = YES;

15
啊哈,这里的“userInteractionEnabled”属性很关键(因为其他配置可以并且最好在storyboard中设置)。标签默认关闭交互以便通过它们传递触摸 - 但在这种情况下,它们需要观察触摸才能激活手势识别器。谢谢! - Marchy
1
太棒了!我只是在一个标签上添加了一个点击手势,完全忘记启用用户交互。谢谢! - Mike Critchley

39

如果您正在使用Storyboards,可以在Storyboard中完成整个过程而无需编写额外的代码。向Storyboard中添加一个标签,然后向标签添加一个轻击手势。在Utilities面板中,确保为标签选中了“用户交互启用”复选框。从轻击手势(位于Storyboard中您的视图控制器底部),在您的ViewController.h文件中按Ctrl +单击并拖动,创建一个操作。然后在ViewController.m文件中实现操作。


该方法也可仅使用界面构建器而不使用故事板来实现。 - Gomino
确保在Attributes检查器中的View部分中选中了“启用用户交互”,而不仅仅是辅助功能特性。 - SeanR

18

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

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

我将一个NSMutableString添加为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

如何在UILabel上添加轻拍手势

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


4
您可以使用UIButton,将文本设置为您想要显示的内容。 如果您不想让按钮看起来像按钮,也可以进行自定义。

1
关于这个问题,我一直有困扰,即UIButton左对齐多行文本。即使我将左对齐设置为居中,它仍然会发生。 - Happy
我确实尝试了一下UIButton,它非常不错。只是多行按钮有些问题。谢谢。 - Happy

2

Swift版本: 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:")

2

这在 Xcode 12 和 Swift 5 中非常有效。

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

userLabel?.isUserInteractionEnabled = true

userLabel?.addGestureRecognizer(tapAction)

像这样的操作方法 -

@objc func actionTapped(_ sender: UITapGestureRecognizer) {
        print("tapped")
    }

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

1
如果您想在按钮中使用多行文本,则需要创建一个带有多行文本的UILabel并将其添加为子视图到您的按钮中。
例如:
yourLabel=[Uilabel alloc]init];
yourLabel.frame=yourButtom.Frame;//(frame size should be equal to your button's frame)
[yourButton addSubView:yourLabel]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接