简体   繁体   中英

Drag event in subview of UIScrollView

How can I add a drag event to a subview of a UIScrollView? The structure is the following:

-UIView
   -UIScrollView
      -UIView
      -UIView
        ...

I tried to start with the following:

-(void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *aTouch = [touches anyObject];
CGPoint location = [aTouch locationInView:self.superview.superview];
[UIView beginAnimations:@"Dragging A DraggableView" context:nil];
self.frame = CGRectMake(location.x, location.y, 
                        self.frame.size.width, self.frame.size.height);
[UIView commitAnimations];

}

But nothing happens! Help would be very much appreciated. Thanks

Just incase anyone finds this question like I did, I solved this problem by adding a gesture recognizer to the subviews in the scrollview. The gesture recognizer will handle the touch event itself.

Bruno, one possibility is to use the gesture recognizers, as Scott mentions.

Another possibility is to use the touchesMoved: method you mention. Using the touchesMoved: method requires you to implement another three methods, touchesBegan:, touchesEnded:, touchesCancelled:. They cover the phases of the finger touching the screen:

  • First contact (touchesBegan) allows you to set up variables as needed.
  • Continuous move (touchesMoved) allows you to track the move and move your content continuously.
  • And finally removing the finger (touchesEnded) where you can finalize any changes you want to keep.
  • touchesCancelled is required for clean-up if the gesture is interrupted (by phone call, or some other controller grabbing the touch event).

You need all four methods on the same class, otherwise a superclass implementing the method will grab the touch processing and your code won't run as expected.

Regards, nobi

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM