Skip to content

Instantly share code, notes, and snippets.

@calimarkus
Created June 19, 2022 12:33
Show Gist options
  • Save calimarkus/dc08240c1f382c85d5076db9767ea861 to your computer and use it in GitHub Desktop.
Save calimarkus/dc08240c1f382c85d5076db9767ea861 to your computer and use it in GitHub Desktop.
Manual touch handling across multiple buttons
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
[super touchesBegan:touches withEvent:event];
UIView *button = [self viewForTouches:touches event:event];
[self setHighlightedView:button];
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
[super touchesMoved:touches withEvent:event];
UIView *button = [self viewForTouches:touches event:event];
[self setHighlightedView:button];
}
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event {
[super touchesCancelled:touches withEvent:event];
[self setHighlightedView:nil];
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
[super touchesEnded:touches withEvent:event];
UIView *button = [self viewForTouches:touches event:event];
[self handleTouchUpForButton:button];
[self setHighlightedView:nil];
}
- (void)handleTouchUpForButton:(UIView*)sender {
// handle touch for sender
}
- (void)setHighlightedView:(UIView *)highlightedView {
// highlight currently pressed button (highlightedView)
}
- (UIView*)viewForTouches:(NSSet*)touches event:(UIEvent*)event {
CGPoint location = [[touches anyObject] locationInView:self];
// find view
UIView *view = nil;
for (UIView *button in self.allButtons) {
CGRect rect = [self convertRect:button.frame fromView:button.superview];
if (CGRectContainsPoint(rect, location)) {
view = button;
break;
}
}
return view;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment