user3884889
user3884889

Reputation: 41

How to add drag gesture to uiview in uiscrollview ios

I'm trying to add the move gesture of uiview inside uiscrollview but I can not disable the srcoll event of uiscrollview. I have implemented the UIScrollview with paging enable in Main class. In another class, i added uiview in it, add gesture for it but i dont know how to disable scrolling of uiscrollview.

Please give me some advice. Thanks in advance.

Upvotes: 0

Views: 1126

Answers (1)

Prasad
Prasad

Reputation: 6034

You need to communicate from your UIView class with gesture in it by means of delegate to the main class asking scroll view to stop scrolling and later on enabling it. I have enclosed the code.

Your UIView.h file

@protocol MyUIViewProtocol <NSObject>

- (void)setScrollViewScrollEnabled:(BOOL)enabled;

@end

@interface MyUIView : UIView

@property (weak, nonatomic) id<MyUIViewProtocol> delegate;

@end

Your UIView.m file

@implementation MyUIView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code

        [self setBackgroundColor:[UIColor redColor]];
        UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panGestureMade:)];
        [self addGestureRecognizer:panGesture];
    }
    return self;
}

- (void)panGestureMade:(UIPanGestureRecognizer *)recognizer
{
    CGPoint pointsToMove = [recognizer translationInView:self];
    [self setCenter:CGPointMake(self.center.x + pointsToMove.x, self.center.y + pointsToMove.y)];
    [recognizer setTranslation:CGPointZero inView:self];

    //Disable the scroll when gesture begins and enable the scroll when gesture ends.
    if (self.delegate && [self.delegate respondsToSelector:@selector(setScrollViewScrollEnabled:)]) {
        if (recognizer.state == UIGestureRecognizerStateBegan) {
            [self.delegate setScrollViewScrollEnabled:NO];
        }
        else if (recognizer.state == UIGestureRecognizerStateCancelled || recognizer.state == UIGestureRecognizerStateEnded) {
            [self.delegate setScrollViewScrollEnabled:YES];
        }
    }
}

Your main class file with scroll view in it.

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 320, 568)];
    [self.scrollView setBackgroundColor:[UIColor yellowColor]];
    [self.scrollView setPagingEnabled:YES];
    [self.scrollView setContentSize:CGSizeMake(320 * 3, 568)];
    [self.view addSubview:self.scrollView];

    MyUIView *view = [[MyUIView alloc] initWithFrame:CGRectMake(40, 100, 100, 100)];
    view.delegate = self;
    [self.scrollView addSubview:view];
}

- (void)setScrollViewScrollEnabled:(BOOL)enabled
{
    [self.scrollView setScrollEnabled:enabled];
}

Hope this answer helps you.

Upvotes: 1

Related Questions