Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIView: How to check if touches ended inside the same view in which they began

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?

like image 973
ma11hew28 Avatar asked Apr 23 '11 02:04

ma11hew28


2 Answers

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
}
like image 158
ergunkocak Avatar answered Nov 03 '22 09:11

ergunkocak


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.

like image 29
ma11hew28 Avatar answered Nov 03 '22 07:11

ma11hew28