在 UILabel 中处理触摸事件并将其连接到 IBAction

好的,我用 Interface Builder 创建了一个 UILabel,它显示一些“点击开始”的默认文本。

当用户点击 UILabel时,我希望它触发一个 IBAction 方法: -(IBAction)next;,它更新标签上的文字,以表示一些新的内容。
如果这允许我简单地将一个连接从我的方法拖动到我的标签,然后在内部选择触摸,就像使用一个按钮一样,那将是非常方便的。可惜没有雪茄。

所以不管怎样,我想我的问题是,我是否必须继承 UILabel才能让它工作?或者有什么方法可以在标签上拖动一个按钮,但使其0% 不透明。还是我错过了一个更简单的解决方案?

98390 次浏览

UILabel inherits from UIView which inherits from UIResponder. All UIresponder objects can handle touch events. So in your class file which knows about your view (which contains the UIlabel) implement:

-(void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event;

In interface builder set the UILabel's tag value. when touches occur in your touchesBegan method, check the tag value of the view to which the tag belongs:

UITouch *touch = [touches anyObject];


if(touch.view.tag == MY_TAG_VAL)
label.text = @"new text";

You connect your code in your class file with the UILabel object in interface builder by declaring your UILabel instance variable with the IBOutlet prefix:

IBOutlet UILabel *label;

Then in interface builder you can connect them up.

You can use a UIButton, make it transparent, i.e. custom type without an image, and add a UILabel on it (centered). Then wire up the normal button events.

Check it out:

UILabel *label = ...
label.userInteractionEnabled = YES;
UITapGestureRecognizer *tapGesture =
[[UITapGestureRecognizer alloc] initWithTarget:self
action:@selector(labelTap)];
[label addGestureRecognizer:tapGesture];

The trick is to enable user interaction.

Swift 3

You have an IBOutlet

@IBOutlet var label: UILabel!

In which you enable user interaction and add a gesture recognizer

label.isUserInteractionEnabled = true
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(userDidTapLabel(tapGestureRecognizer:)))
label.addGestureRecognizer(tapGesture)

And finally, handle the tap

func userDidTapLabel(tapGestureRecognizer: UITapGestureRecognizer) {
// Your code goes here
}