本文介绍了直接将UITapGestureRecognizer实现到UIView而不是ViewController不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

的实例MenuButtonImageView homeScreenViewController的子视图.view

我实现了 touchesBegan:withEvent: touchesMoved:withEvent: touchesEnded:withEvent:也可以正常工作。

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

问题:不知何故 handleSingleFingeredTap:永远不会被调用。这可能是什么问题?

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


推荐答案

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

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.

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

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.

这篇关于直接将UITapGestureRecognizer实现到UIView而不是ViewController不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 12:11