105

好的,所以我UILabel在界面生成器中创建了一个显示一些“点击开始”的默认文本。

当用户点击UILabel我希望它触发 IBAction 方法时: -(IBAction)next;它会更新标签上的文本以说出新内容。
如果这允许我简单地将连接从我的方法拖到我的标签上,然后像使用按钮一样选择内部修饰,那将非常方便。但唉,没有雪茄。

所以无论如何,我想我的问题是,我是否必须进行子类化UILabel才能使其正常工作?或者有什么方法可以在标签上拖动一个按钮,但使其不透明为 0%。还是我缺少一个更简单的解决方案?

4

4 回答 4

255

看看这个:

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

诀窍是启用用户交互。

于 2011-07-15T18:52:58.140 回答
70

UILabel 继承自 UIView,而 UIView 继承自 UIResponder。所有 UIresponder 对象都可以处理触摸事件。所以在你知道你的视图(包含 UIlabel)的类文件中实现:

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

在界面生成器中设置 UILabel 的标签值。当 touchesBegan 方法中发生触摸时,检查标签所属视图的标签值:

UITouch *touch = [touches anyObject];

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

通过使用 IBOutlet 前缀声明 UILabel 实例变量,您可以将类文件中的代码与接口构建器中的 UILabel 对象连接起来:

IBOutlet UILabel *label;

然后在界面生成器中,您可以将它们连接起来。

于 2010-07-03T00:37:49.920 回答
31

您可以使用 UIButton,使其透明,即没有图像的自定义类型,并在其上添加 UILabel(居中)。然后连接正常的按钮事件。

于 2010-07-03T00:48:42.357 回答
22

斯威夫特 3

你有一个 IBOutlet

@IBOutlet var label: UILabel!

您可以在其中启用用户交互并添加手势识别器

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

最后,处理水龙头

func userDidTapLabel(tapGestureRecognizer: UITapGestureRecognizer) {
  // Your code goes here
}
于 2017-07-13T14:15:47.370 回答