为什么UITapGestureRecognizer不能在keyWindow(全屏)的子视图中工作?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了为什么UITapGestureRecognizer不能在keyWindow(全屏)的子视图中工作?相关的知识,希望对你有一定的参考价值。

我在这里问(UIView added as an UIWindow subview doesn't respond to taps),但我认为它应该有自己的问题。

如果我以这种方式设置子类UIView(自定义视图),我无法在视图中使用手势:

CustomView *customView = [[[CustomView alloc] initWithFrame:[UIApplication sharedApplication].keyWindow.frame];

customView.frame = [UIApplication sharedApplication].keyWindow.bounds; // leaves space at bottom of screen if not here

[[UIApplication sharedApplication].keyWindow addSubview:customView];

但如果我这样设置,手势就可以了:

CustomView *customView = [[[CustomView alloc] initWithFrame:[UIApplication sharedApplication].keyWindow.frame];

customView.frame = [UIApplication sharedApplication].keyWindow.bounds; // leaves space at bottom of screen if not here

[[UIApplication sharedApplication].windows[0] addSubview:customView];

请注意,使用.windows [0]而不是.keyWindow意味着状态栏仍然存在,因此当我取消隐藏customView以获得空白全屏时,我必须隐藏它。

在customView中:

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];

    id mainView;
    if (self)
    {
        NSArray *subviewArray = [[NSBundle mainBundle] loadNibNamed:@"CustomNib" owner:self options:nil];
        mainView = [subviewArray objectAtIndex:0];
    }
    return mainView;
}

这里是手势设置,也在customView中:

UITapGestureRecognizer *singleFingerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)];
[self addGestureRecognizer:singleFingerTap];

当视图是.keyWindow的子视图时手势识别器无法工作的任何想法,但是当视图是.windows [0]的子视图时有效吗?

答案

initWithFrame,你将返回一个UIView ---不是CustomView的一个例子。

您可能希望您的CustomView代码如下所示:

#import "CustomView.h"

@implementation CustomView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];

    UIView *mainView;
    if (self)
    {
        NSArray *subviewArray = [[NSBundle mainBundle] loadNibNamed:@"CustomNib" owner:self options:nil];
        mainView = [subviewArray objectAtIndex:0];
        mainView.frame = self.bounds;
        mainView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        [self addSubview:mainView];
        [self setupTap];
    }
    return self;
}

- (void) setupTap {

    UITapGestureRecognizer *singleFingerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)];
    [self addGestureRecognizer:singleFingerTap];

}

- (void)handleTap:(UIGestureRecognizer *)g {
    NSLog(@"Tap in CustomView!");
}

@end

以上是关于为什么UITapGestureRecognizer不能在keyWindow(全屏)的子视图中工作?的主要内容,如果未能解决你的问题,请参考以下文章

什么条件会导致 UITapGestureRecognizer 失败但 touchesBegan 成功?

iOS 为啥不能从 UITapGestureRecognizer 调用方法 collectionView:didSelectItemAtIndexPath:?

为啥我的 UITapGestureRecognizer 方法没有快速调用 Navigationbar titleView

使用UITapGestureRecognizer传递参数

为什么UITapGestureRecognizer不能在keyWindow(全屏)的子视图中工作?

为啥当我添加 UITapGestureRecognizer 处理程序方法时 TableView 委托方法停止工作