Created
September 14, 2018 18:25
-
-
Save bnickel/3a96d0f3b2c97c259fb98fb70c7c6498 to your computer and use it in GitHub Desktop.
Enlarges the tap radius of small UICollectionViews
This file contains 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
#import <UIKit/UIKit.h> | |
IB_DESIGNABLE | |
@interface SEUIEnlargedTapRadiusCollectionView : UICollectionView | |
@property (nonatomic, assign) IBInspectable CGFloat enlargedTapRadius; | |
@end |
This file contains 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
#import "SEUIEnlargedTapRadiusCollectionView.h" | |
CGPoint ShiftNearbyPointInside(CGPoint point, CGRect bounds, CGFloat radius) { | |
if (point.y < 0 && point.y > -radius) { | |
point.y = 5; | |
} | |
if (point.y > CGRectGetMaxY(bounds) && point.y < CGRectGetMaxY(bounds) + radius) { | |
point.y = CGRectGetMaxY(bounds) - 5; | |
} | |
return point; | |
} | |
@implementation SEUIEnlargedTapRadiusCollectionView | |
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event | |
{ | |
return [super hitTest:ShiftNearbyPointInside(point, self.bounds, self.enlargedTapRadius) withEvent:event]; | |
} | |
/** | |
@discussion | |
hitTest:withEvent: is good enough to get the cell to highlight on touch (become the first responder) but then the actual tap calculations are based on the touch, which is not translated. We will cheat like hell here, it may not be amazing for weird edge cases like dragging. | |
*/ | |
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event | |
{ | |
[super touchesEnded:touches withEvent:event]; | |
if (touches.count != 1) { | |
return; | |
} | |
UITouch *touch = [touches anyObject]; | |
CGPoint locationInView = [touch locationInView:self]; | |
UIView *desiredHitView = [self hitTest:locationInView withEvent:event]; | |
UIView *actualHitView = [super hitTest:locationInView withEvent:event]; | |
if (desiredHitView == actualHitView) { | |
return; | |
} | |
while (desiredHitView && ![desiredHitView isKindOfClass:[UICollectionViewCell class]]) { | |
desiredHitView = desiredHitView.superview; | |
} | |
if (desiredHitView == nil) { | |
return; | |
} | |
NSIndexPath *indexPath = [self indexPathForCell:(UICollectionViewCell *)desiredHitView]; | |
if (indexPath) { | |
[self.delegate collectionView:self didSelectItemAtIndexPath:indexPath]; | |
} | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment