2011-06-15 50 views
26

我试图将手势识别器附加到我自己的UILabel的子类中,但它不起作用。你能帮助我了解什么是错的代码是否有可能将UITapGestureRecognizer附加到UILabel子类


@interface Card : UILabel { 

} 

- (void) addBackSideWord; 

@end 

#import "Card.h" 

@implementation Card 
- (id)initWithFrame:(CGRect)frame { 

    if ((self = [super initWithFrame:frame])) { 

     UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc] 
         initWithTarget:self action:@selector(addBackSideWord)]; 
     [tapRecognizer setNumberOfTouchesRequired:2]; 
     [tapRecognizer setDelegate:self]; 
     [self addGestureRecognizer:tapRecognizer]; 
    } 

    return self; 
} 

- (void) addBackSideWord { 

    //do something 
} 
@end 

回答

68

您的代码应该可以正常工作,您可能需要修复的唯一的事情就是用户交互的的UILabel是默认情况下禁用,因此手势识别器不接收任何触摸事件。手动尝试通过(例如,在init()方法)中添加这一行到您的代码启用:

self.userInteractionEnabled = YES; 
+1

谢谢您的解答!我花了24小时阅读文档,并没有注意到这个简单的伎俩。只希望它对我有用:) – Michael 2011-06-15 09:50:46

15

是的,这是可能的,任何类继承UIView

不要忘记启用用户交互。

self.userInteractionEnabled = YES; 
+1

谢谢你的答案!我花了24小时阅读文档,并没有注意到这个简单的伎俩。只是希望它对我有用:) – Michael 2011-06-15 09:51:07

+0

@迈克尔:有时会发生.. :) – Jhaliya 2011-06-15 10:02:50

2

可以使用以下代码来对UILable添加敲击手势: -

步骤1:

Delegate "UIGestureRecognizerDelegate" to your viewcontroller.h 

for example: 
    @interface User_mail_List : UIViewController<UIGestureRecognizerDelegate> 

步骤2:

//create you UILable 
UILabel *title_lbl= [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 30)]; 
[title_lbl setText:@"u&me"]; 
[title_lbl setUserInteractionEnabled:YES]; 
[yourView addSubview:title_lbl]; 

步骤3:

UITapGestureRecognizer *tap= [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(Prof_lbl_Pressed:)];//your action selector 
[tap setNumberOfTapsRequired:1]; 
title_lbl.userInteractionEnabled= YES; 
[title_lbl addGestureRecognizer:tap]; 

第4步:

-(void)Prof_lbl_Pressed:(id)sender{ 
    //write your code action 
} 

感谢,

相关问题