Skip to content

Instantly share code, notes, and snippets.

@nonamelive
Last active July 20, 2016 15:17
Show Gist options
  • Save nonamelive/8287674ea7cfc1a9d2ff to your computer and use it in GitHub Desktop.
Save nonamelive/8287674ea7cfc1a9d2ff to your computer and use it in GitHub Desktop.
Prevent UINavigationBar from stealing touches
@interface DMNavigationBar : UINavigationBar
@property (nonatomic, assign) BOOL shouldOnlyReceiveTouchEventsInsideNavigationBar;
@end
#import "DMNavigationBar.h"
#import "UIResponder+FirstResponder.h"
@interface DMNavigationBar ()
@property (nonatomic, assign) BOOL changingUserInteraction;
@property (nonatomic, assign) BOOL userInteractionChangedBySystem;
@end
@implementation DMNavigationBar
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event
{
if (self.shouldOnlyReceiveTouchEventsInsideNavigationBar)
{
if (self.userInteractionChangedBySystem && self.userInteractionEnabled == NO)
{
return [super hitTest:point withEvent:event];
}
UIView *firstResponder = [UIResponder currentFirstResponder];
BOOL isFirstResponderADescendantView = [firstResponder isKindOfClass:[UIView class]] && [firstResponder isDescendantOfView:self];
if ([self pointInside:point withEvent:event] || isFirstResponderADescendantView)
{
self.changingUserInteraction = YES;
self.userInteractionEnabled = YES;
self.changingUserInteraction = NO;
}
else
{
self.changingUserInteraction = YES;
self.userInteractionEnabled = NO;
self.changingUserInteraction = NO;
}
}
return [super hitTest:point withEvent:event];
}
- (void)setUserInteractionEnabled:(BOOL)userInteractionEnabled
{
if (self.shouldOnlyReceiveTouchEventsInsideNavigationBar)
{
if (!self.changingUserInteraction)
{
self.userInteractionChangedBySystem = YES;
}
else
{
self.userInteractionChangedBySystem = NO;
}
}
[super setUserInteractionEnabled:userInteractionEnabled];
}
@end
@interface UIResponder (FirstResponder)
+ (id)currentFirstResponder;
@end
#import "UIResponder+FirstResponder.h"
static __weak id currentFirstResponder;
@implementation UIResponder (FirstResponder)
+ (id)currentFirstResponder
{
currentFirstResponder = nil;
[[UIApplication sharedApplication] sendAction:@selector(findFirstResponder:) to:nil from:nil forEvent:nil];
return currentFirstResponder;
}
- (void)findFirstResponder:(id)sender
{
currentFirstResponder = self;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment