Search code examples
objective-cios7uiviewanimationuiswipegesturerecognizer

Progressively sliding a view


I currently have a menu that I slide in from the left. I have add UITapGestureRecognizer to the main view. Something like this:

UISwipeGestureRecognizer *recognizer;
    recognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(toggleMenu:)];
    [recognizer setDirection:UISwipeGestureRecognizerDirectionRight];
    [self.view addGestureRecognizer:recognizer];

toggleMenu: then does something like this:

int targetX = 260;
_menuIsShowing = YES;

[UIView animateWithDuration:0.25 animations:^{
        [_currentVC.view setFrame:CGRectMake(targetX, [_currentVC.view frame].origin.y,
                                             [_currentVC.view frame].size.width, [_currentVC.view frame].size.height)];
    } completion:^(BOOL finished) {

        [[NSNotificationCenter defaultCenter] postNotificationName:NOTIFY_resetNumberPadButtons object:self];

    }];

This works, but isn't pretty. When the user swipes far enough toggleMenu: is called and the menu comes in from the left at once. I would however like for the menu to come in gradually as the user swipes - so basically to link the swipe distance with how much of the menus is showing.

Thanks


Solution

  • You want to use UIPanGestureRecognizer. Add it to your self.view and use the translationInView: method to get the current CGPoint of the pan and reset the frame of your sliding view accordingly. You can also force the gesture recognizer to work only from left to right using the velocityInView method and checking against the horizontal (x) component.

    CGPoint velocity = [recognizer velocityInView:yourView];
    if (velocity.x > 0) {
        //left to right 
    }
    

    The best user experience in this case would be achieved using the UIScreenEdgePanGestureRecognizer which inherits from the former one. With this you can specify the edges which the user can drag from.

    Apple docs always help: https://developer.apple.com/library/ios/documentation/uikit/reference/UIPanGestureRecognizer_Class/Reference/Reference.html https://developer.apple.com/library/ios/documentation/uikit/reference/UIScreenEdgePanGestureRecognizer_class/Reference/Reference.html