1
votes

I asked here (UIView added as an UIWindow subview doesn't respond to taps) but I thought it deserved its own question.

If I set up a subclassed UIView (CustomView) this way, I can't get gestures to work within the view:

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];

But if I set up this way, gestures work fine:

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];

Note that using .windows[0] instead of .keyWindow means the status bar is still there, so I have to hide that when I unhide customView to get an empty full screen.

Within 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;
}

And here's the gesture setup, also within customView:

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

Any ideas why the gesture recognizer doesn't work when the view is a subview of .keyWindow but works when the view is a subview of .windows[0]?

1

1 Answers

0
votes

In initWithFrame, you are returning a UIView --- not an instance of CustomView.

You probably want your CustomView code to look like this:

#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