8

In AcaniUsers, I've created a grid of ThumbView : UIView instances inside of a UITableView. All thumbViews have a width of kThumbSize. How do I detect if touches ended inside the same view in which they began?

ma11hew28
  • 121,420
  • 116
  • 450
  • 651

2 Answers2

9

In the view extension you use;

Swift 4:

open override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    super.touchesEnded(touches, with: event)
    guard let touchPoint = touches.first?.location(in: self) else { return }
    guard self.bounds.contains(touchPoint) else { return }
    // Do items for successful touch inside the view
}
ergunkocak
  • 3,334
  • 1
  • 32
  • 31
3

The following works, but I'm not sure if it's the best way to go about it. I think so though.

Since all thumbViews have a width of kThumbSize, just check in touchesEnded that the x-coordinate of the locationInView of the UITouch instance (assuming self.multipleTouchEnabled = NO) is less than or equal to kThumbSize. This means the touches ended inside the thumbView. No need to check the y-coordinate because if the touches move vertically, the tableView, which contains the thumbViews, scrolls and the touches are cancelled.

Do the following in ThumbView : UIView (whose instances are subviews of a UITableView):

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    NSLog(@"touchesEnded %@", touches);
    CGPoint touchPoint = [[touches anyObject] /* only one */ locationInView:self];
    if (touchPoint.x >= 0.0f && touchPoint.x <= kThumbSize) {
        [(ThumbsTableViewCell *)self.superview.superview thumbTouched:self];
    }
}

To only register touches on one thumbView at a time, you also probably want to set self.exclusiveTouch = YES; in the init instance method of ThumbView.

ma11hew28
  • 121,420
  • 116
  • 450
  • 651
  • 2
    You can write nicer code by doing this: `if (CGRectContainsPoint(self.bounds, touchPoint)) { ... }`. :) – BastiBen Sep 02 '11 at 08:46