Implementing UITapGestureRecognizer directly into UIView instead of ViewController does not work

爱⌒轻易说出口 提交于 2019-12-11 06:51:40

问题


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.



来源:https://stackoverflow.com/questions/12201924/implementing-uitapgesturerecognizer-directly-into-uiview-instead-of-viewcontroll

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!