直接将UITapGestureRecognizer实现到UIView而不是ViewController不起作用

时间:2012-08-30 17:01:24

标签: objective-c ios5 uiimageview uigesturerecognizer

正如this SO-answer中所述,我正在尝试在UITapGestureRecognizer的子类中实现UIIMageView。我的方法可以在下面找到。

MenuButtonImageView的实例是homeScreenViewController.view的子视图。

我也实施了touchesBegan:withEvent:touchesMoved:withEvent:touchesEnded:withEvent:,并且工作正常。

问题:从不会调用handleSingleFingeredTap:。这可能是什么问题?

@interface MenuButtonImageView : UIImageView

@property (nonatomic, weak) IBOutlet HomescreenViewController *homeScreenViewController;
@property (nonatomic, readwrite) Visibility visibility;

- (void)handleSingleFingeredTap:(UITapGestureRecognizer *)recognizer;

@end

@implementation MenuButtonImageView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.visibility = HIDDEN;
        self.userInteractionEnabled = YES;
        UITapGestureRecognizer * singleFingeredTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleFingeredTap:)];
        singleFingeredTap.numberOfTapsRequired = 1;
        [self addGestureRecognizer:singleFingeredTap];
    }
    return self;
}

- (void)handleSingleFingeredTap:(UITapGestureRecognizer *)recognizer {
    NSLog(@"handleTap was called"); // This method is not called!
    [self toggleMainMenu];
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { ... }
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event { ... }
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { ... }

@end

1 个答案:

答案 0 :(得分:1)

您可以使用initWithFrame方法添加识别器。检查您的视图是否以这种方式初始化。它可以使用其他构造函数(如initWithCoder)创建,然后您的代码不会被执行。在initWithFrame方法中放置一个断点来查找。

您可以将代码放在单独的方法中,并从两个构造函数中调用它。这取决于你如何使用它。从代码创建视图时,initWithFrame非常常见。