Implementing UITapGestureRecognizer directly into

2019-07-30 19:17发布

问题:

As explained in this SO-answer I am trying to implement UITapGestureRecognizer in a subclass of UIIMageView. My approach can be found below.

An instance of MenuButtonImageView is a subview of homeScreenViewController.view.

I implemented touchesBegan:withEvent:, touchesMoved:withEvent: and touchesEnded:withEvent: too and do work fine.

Problem: Somehow handleSingleFingeredTap: is never called. What could be the problem with this?

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

You add the recognizer in initWithFrame method. Check if your view is initialized this way. It may be created with another constructor like initWithCoder, and then your code is not executed. Put a breakpoint inside initWithFrame method to find out.

You can put the code in a separate method and call it from both constructors. It depends on how you use it. The initWithFrame is used quite common when you create a view from code.