detecting the [UITouch view] in touchesMoved method

6.8k views Asked by At

I wish to drag from one subview to another within my application (and connect them with a line), and so I need to keep track of the current view being touched by the user.

I thought that I could achieve this by simply calling [UITouch view] in the touchesMoved method, but after a quick look at the docs I've found out that [UITouch view] only returns the view in which the initial touch occurred.

Does anyone know how I can detect the view being touched while the drag is in progress?

3

There are 3 answers

0
Matt Carr On BEST ANSWER

After a bit more research I found the answer.

Originally, I was checking for the view like so:

if([[touch view] isKindOfClass:[MyView* class]])
{
   //hurray.
}

But, as explained in my question, the [touch view] returns the view in which the original touch occurred. This can be solved by replacing the code above with the following:

if([[self hitTest:[touch locationInView:self] withEvent:event] isKindOfClass:[MyView class]])
{
    //hurrraaay! :)
}

Hope this helps

1
Max On

UIView is subclass of UIResponder. So you can override touches ended/ began methods in your custom class, that inherits from UIView. Than you should add delegate to that class and define protocol for it. In the methods

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event

or whatever interactions you need just send appropriate message to object's delegate also passing this object. E.g.

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
   [delegate touchesBeganInView: self withEvent: event];
}
0
Evgen Bodunov On

And my way:

- (void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [touches anyObject];
    if ([self pointInside:[touch locationInView:self] withEvent:event]) {
        [self sendActionsForControlEvents:UIControlEventTouchUpInside];
    } else {
        [self sendActionsForControlEvents:UIControlEventTouchUpOutside];
    }
}