【问题标题】:Is it possible to attach UITapGestureRecognizer to UILabel subclass是否可以将 UITapGestureRecognizer 附加到 UILabel 子类
【发布时间】:2011-06-15 09:28:49
【问题描述】:

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

【问题讨论】:

    标签: iphone ios xcode ios4


    【解决方案1】:

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

    self.userInteractionEnabled = YES;
    

    【讨论】:

    • 感谢您的回答!我花了 24 小时阅读文档,并没有注意到这个简单的技巧。只是希望它对我有用:)
    【解决方案2】:

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

    不要忘记启用用户交互。

    self.userInteractionEnabled = YES;
    

    【讨论】:

    • 感谢您的回答!我花了 24 小时阅读文档,并没有注意到这个简单的技巧。只是希望它对我有用:)
    • @Michael : 有时会发生 .. :)
    【解决方案3】:

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

    第一步:

     Delegate "UIGestureRecognizerDelegate" to your viewcontroller.h
    
     for example:
         @interface User_mail_List : UIViewController<UIGestureRecognizerDelegate>
    

    第二步:

    //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
    }
    

    谢谢,

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-27
      相关资源
      最近更新 更多