Skip to content

Instantly share code, notes, and snippets.

@bnickel
Created September 14, 2018 18:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bnickel/3a96d0f3b2c97c259fb98fb70c7c6498 to your computer and use it in GitHub Desktop.
Save bnickel/3a96d0f3b2c97c259fb98fb70c7c6498 to your computer and use it in GitHub Desktop.
Enlarges the tap radius of small UICollectionViews
#import <UIKit/UIKit.h>
IB_DESIGNABLE
@interface SEUIEnlargedTapRadiusCollectionView : UICollectionView
@property (nonatomic, assign) IBInspectable CGFloat enlargedTapRadius;
@end
#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