在屏幕上滑动UIView

时间:2015-09-24 12:22:29

标签: ios objective-c uiview gesture uigravitybehavior

我希望能够拥有一个UIView(或者,如果必要的话,还有UIViewController),可以在屏幕上拖动' /轻弹/滑动 - 但是锁定到垂直轴(所以视图会在屏幕上上下移动以显示下面的视图。这有点像Facebook应用程序的Web视图。

这可能是用UIGravityBehavior实现的吗?

任何想法都会很棒。

1 个答案:

答案 0 :(得分:1)

我之前使用UIPanGestureRecognizer做了类似的事情。以下是这将如何工作:

float slidingMenuOffsetSum;

    - (void)handleSlidingMenuPan:(UIPanGestureRecognizer *)gestureRecognizer {
        CGPoint translation = [gestureRecognizer translationInView:_slidingMenuView];

        slidingMenuOffsetSum += translation.y;
        CGPoint newSlidingMenuCenter = CGPointMake(_slidingMenuView.center.x, _slidingMenuView.center.y + translation.y);

        if (_slidingMenuView.frame.origin.y <= 512 && _slidingMenuView.frame.origin.y >= 0) {
            _slidingMenuView.center = newSlidingMenuCenter;
        }

        [gestureRecognizer setTranslation:CGPointZero inView:_slidingMenuView];

        if (gestureRecognizer.state == UIGestureRecognizerStateEnded) {
            [UIView animateWithDuration:0.3
                animations:^{
                    [_slidingMenuView setUserInteractionEnabled:false];
                    if (slidingMenuOffsetSum > 0) {
                        if (slidingMenuOffsetSum > _slidingMenuView.frame.size.height / 4) {
                            [self setSlidingMenuHidden:false];
                        } else {
                            [self returnSlidingMenuToPosition];
                        }
                    } else {
                        if (slidingMenuOffsetSum < -_slidingMenuView.frame.size.height / 4) {
                            [self setSlidingMenuHidden:true];
                        } else {
                            [self returnSlidingMenuToPosition];
                        }
                    }
                }
                completion:^(BOOL finished) {
                    slidingMenuOffsetSum = 0;
                    [_slidingMenuView setUserInteractionEnabled:true];
                }];
        }
    }

您可以调整滑动菜单可以移动的值,以及用于检测视图是否应该返回其原始位置的阈值,或者例如。离开屏幕。