xcode 是否可以将 UITapGestureRecognizer 附加到 UILabel 子类

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6355650/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 21:16:03  来源:igfitidea点击:

Is it possible to attach UITapGestureRecognizer to UILabel subclass

iphoneiosxcodeios4

提问by Michael

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

我正在尝试将手势识别器附加到我自己的类,它是 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

回答by Vladimir

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):

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

self.userInteractionEnabled = YES;

回答by Jhaliya

Yes, that's possible,Any class inheritedfrom UIView.

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

Do'nt forget to enable user interaction.

不要忘记启用用户交互。

self.userInteractionEnabled = YES;

回答by Kupendiran iOS

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

您可以使用以下代码在 UILable 上添加点击手势:-

Step 1:

第1步:

 Delegate "UIGestureRecognizerDelegate" to your viewcontroller.h

 for example:
     @interface User_mail_List : UIViewController<UIGestureRecognizerDelegate>

Step 2:

第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:

第 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,

谢谢,