How do I implement a draggable UIView subclass within a UIScrollView?
I have a rather tricky scrolling scenerio I need to get sorted. I have a parent UIScrollView with a single container view containing two child UIView subclasses. Call them viewA and viewB. The UIScrollView has been constrained to scroll/zoom horizontally. ViewA and ViewB are layed out as horizontal strips, one above the other. The bounds of viewA and viewB exceed the bounds of the scrollView and are revealed during scroll/zoom as is normal. So far so good.
Here is where things get a bit tricky: I need to be able to drag viewB vertically as well as horizontally. I prefer not to nest viewB within it's own scrollView.
My question is, what is the correct way to implement simple vertical scrolling for viewB while still having it behave correctly with respect to the scrollView? Do I simply implement the four touch sequence methods: begin/moved/ended/cancelled in viewB, ma开发者_高级运维nipulating viewB's transform matrix and I'm in the clear or is the more to it?
Thanks in advance.
Cheers, Doug
Well, concerning your given scenario, I would solve this as follows:
First of all create a UIView-Subclass, including the nessecary functions, this one is receiving your drag-actions. While this is draggable, you should disable the scrolling of your UIScrollView. Header:
#import <UIKit/UIKit.h>;
@interface ViewB : UIView
{
}
@end
Implementation:
#import "ViewB.h"
@implementation DragView
- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
self.alpha = 0.5;
((UIScrollView*)self.superview.superview).scrollEnabled = NO;
}
- (void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
CGPoint loc = [touch locationInView:self.superview];
self.center = loc;
}
- (void) touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
{
self.alpha = 1.0;
((UIScrollView*)self.superview.superview).scrollEnabled = YES;
}
- (void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
self.alpha = 1.0;
((UIScrollView*)self.superview.superview).scrollEnabled = YES;
}
// Further methods...
@end
精彩评论