在UILabel上执行select器会产生崩溃?

我读过UILabels并不是要回应触摸事件,而是我可以使用UIButton。 然而,我不得不inheritanceUILabel来覆盖另一种方法,所以我想我不如使用一个标签来保持对我的代码的更改至less。

如何让我的标签响应触摸事件? 显示的代码和错误如下。

UILabel *tempLabel = [[UILabel alloc] initWithFrame:CGRectMake(startingPoint, 5, 10, 22)]; tempLabel.text = equationText; tempLabel.font = [UIFont systemFontOfSize:13]; [tempLabel sizeToFit]; [view addSubview:tempLabel]; [tempLabel addTarget:self action:@selector(updateLabel:) forControlEvents:UIControlEventTouchUpInside]; // UNRECOGNIZED SELECTOR SENT TO INSTANCE 

由于UILabel不是控件,因此无法发送-addTarget:action:forControlEvents:消息。 您必须从您的应用程序中删除该行,因为您的标签不是控件,将永远不会响应该消息。 相反,如果你想使用你的标签,你可以将它设置为交互式,并添加一个手势识别器:

 // label setup code omitted UITapGestureRecognizer* tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(updateLabel:)]; [tempLabel setUserInteractionEnabled:YES]; [tempLabel addGestureRecognizer:tap]; [tap release]; // if not using ARC 

手势识别器的callback将被触发的手势识别器的实例传递,而不是像动作信息那样的控件。 要获取触发事件的标签的实例,请使用-view消息传入的手势识别器。 所以,如果你的updateLabel:方法可能如下实现:

 - (void)updateLabel:(UIGestureRecognizer*)recognizer { // Only respond if we're in the ended state (similar to touchupinside) if( [recognizer state] == UIGestureRecognizerStateEnded ) { // the label that was tapped UILabel* label = (UILabel*)[recognizer view]; // do things with your label } } 

此外,手势识别器将调用具有多个状态的操作方法,类似于-touchesBegan:...系列方法中的方法。 在识别器处于适当状态时,应该检查是否只进行了工作。 对于简单的轻击手势识别器,您可能只想在识别器处于UIGestureRecognizerStateEnded状态时进行工作(请参阅上面的示例)。 有关手势识别器的更多信息,请参阅UIGestureRecognizer的文档。

//创build标签

_label = [[UILabel alloc] initWithFrame:CGRectMake(self.view.center.x-75,self.view.frame.size.height-60,150,50)];

 _label.backgroundColor = [UIColor clearColor]; _label.textColor=[UIColor whiteColor]; _label.text = @"Forgot password ?"; UITapGestureRecognizer *recongniser = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction)];//ADD ACTION TO LABEL [_label setUserInteractionEnabled:YES]; [_label addGestureRecognizer:recongniser]; 

//导航到另一个视图

– (void)tapAction //将其添加到标签select器的方法

{

 _forgotviewController=[[ForgotPassword alloc]init]; [self.navigationController pushViewController:self.forgotviewController animated:YES]; 

}

这里最聪明的事情是使用UIButton来做你正在做的事情。

但是,如果你真的想要UILabel子类,请确保将userInteractionEnabled设置为YES。

该文件说 :

新标签对象被configuration为默认忽略用户事件。 如果要处理UILabel的自定义子类中的事件,则必须在初始化对象后明确将userInteractionEnabled属性的值更改为YES。

addTarget: action: forControlEvents:将不起作用,因为UILabel不是来自UIControl 。 一个地方,你可以通过在你的子类中实现UIResponder的touchesBegan:withEvent:方法来捕获你的事件。

这里是UILabel水龙头的快速2.1版本

 let label = UILabel(frameSize) let gesture = UITapGestureRecognizer(target: self, action: "labelTapped:") labelHaveAccount.userInteractionEnabled = true labelHaveAccount.addGestureRecognizer(gesture) func labelTapped(gesture:UIGestureRecognizer!){ //lable tapped }