开发者

Is it possible to attach UITapGestureRecognizer to UILabel subclass

开发者 https://www.devze.com 2023-03-12 22:05 出处:网络
I\'m trying to attach gesture recognizer to my own class which is subclass of UILabel, but it does not work. Can you help me to understand what\'s wrong in the code

I'm trying to attach gesture recognizer to my own class which is subclass of UILabel, but it does not work. Can you help me to understand what's wrong in the code

 
@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


Your code should work fine, the only thing you may need to fix is that user interaction is disabled for UILabel by default, so gesture recogniser does not receive any touch events. Try manually enable it by adding this line to your code (e.g. in init method):

self.userInteractionEnabled = YES;


Yes, that's possible, Any class inherited from UIView.

Do'nt forget to enable user interaction.

self.userInteractionEnabled = YES;


You can use below code to add tap gesture on UILable :-

Step 1:

 Delegate "UIGestureRecognizerDelegate" to your viewcontroller.h

 for example:
     @interface User_mail_List : UIViewController<UIGestureRecognizerDelegate>

Step 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];

Step 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];

Step 4:

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

thanks,

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号