Created
May 16, 2017 03:05
-
-
Save faimin/97cc4e85ea1790710394284c077ca30b to your computer and use it in GitHub Desktop.
extend view's touch area
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
static const void *TouchExtendInsetKey = &TouchExtendInsetKey; | |
static void Swizzle(Class c, SEL orig, SEL new) { | |
Method origMethod = class_getInstanceMethod(c, orig); | |
Method newMethod = class_getInstanceMethod(c, new); | |
if (class_addMethod(c, orig, method_getImplementation(newMethod), method_getTypeEncoding(newMethod))){ | |
class_replaceMethod(c, new, method_getImplementation(origMethod), method_getTypeEncoding(origMethod)); | |
} | |
else { | |
method_exchangeImplementations(origMethod, newMethod); | |
} | |
} | |
@interface UIView() (ZDTouchExtendInsets) | |
@property (nonatomic, assign) UIEdgeInsets zd_touchExtendInsets; | |
@end | |
@implementation UIView (ZDTouchExtendInsets) | |
+ (void)load { | |
static dispatch_once_t onceToken; | |
dispatch_once(&onceToken, ^{ | |
Swizzle(self, @selector(pointInside:withEvent:), @selector(zdPointInside:withEvent:)); | |
}); | |
} | |
#pragma mark TouchExtendInset | |
- (BOOL)zdPointInside:(CGPoint)point withEvent:(UIEvent *)event { | |
if (UIEdgeInsetsEqualToEdgeInsets(self.zd_touchExtendInsets, UIEdgeInsetsZero) || self.hidden) { | |
return [self zdPointInside:point withEvent:event]; | |
} | |
CGRect hitFrame = UIEdgeInsetsInsetRect(self.bounds, self.zd_touchExtendInsets); | |
hitFrame.size.width = MAX(hitFrame.size.width, 0); | |
hitFrame.size.height = MAX(hitFrame.size.height, 0); | |
return CGRectContainsPoint(hitFrame, point); | |
} | |
- (void)setZd_touchExtendInsets:(UIEdgeInsets)zd_touchExtendInsets { | |
UIEdgeInsets zdTouchExtendInsets = UIEdgeInsetsMake(-zd_touchExtendInsets.top, -zd_touchExtendInsets.left, -zd_touchExtendInsets.bottom, -zd_touchExtendInsets.right); | |
objc_setAssociatedObject(self, TouchExtendInsetKey, [NSValue valueWithUIEdgeInsets:zdTouchExtendInsets], OBJC_ASSOCIATION_RETAIN); | |
} | |
- (UIEdgeInsets)zd_touchExtendInsets { | |
return [objc_getAssociatedObject(self, TouchExtendInsetKey) UIEdgeInsetsValue]; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment