如何在PageViewController页面滑动时触发动画

How to trigger animation on PageViewController page swipe

我需要在屏幕上制作从 A 到 B 的视图转换动画。 但是,我希望当用户在屏幕上滑动拇指时发生这种翻译。

我还希望翻译以一种相互跟随的方式依赖于拇指滑动。

我假设我需要某种侦听器,它将跟随我在屏幕上的拇指动作,并且我会以某种方式告诉我的视图在屏幕上向左或向右移动,具体取决于滑动的方向。

我怎样才能做到这一点?

希望对你有所帮助...

UISwipeGestureRecognizer *swipeLeft = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(tappedRightButton:)];
[swipeLeft setDirection:UISwipeGestureRecognizerDirectionLeft];
[self.view addGestureRecognizer:swipeLeft];

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

我会使用 UIPanGestureRecognizer,因为它有更多的控制,例如,如果你移动缓慢,它仍然可以捕捉你的移动位置,然后也许你可以相应地定位你的翻译。

您可以这样做:

var panRecongniser = UIPanGestureRecognizer(target: self, action: Selector("didPanRecongnised:"))

在您的 viewDidLoad 中,然后:

func didPanRecongnised(recongniser: UIPanGestureRecognizer){
    if(recongniser.state == UIGestureRecognizerState.Changed || recongniser.state == UIGestureRecognizerState.Began){
        self.didPanMove(recongniser)
    }else if(recongniser.state == UIGestureRecognizerState.Ended || recongniser.state == UIGestureRecognizerState.Cancelled){
        self.didPanEnd(recongniser)
    }
}

在你的 didPanMove 中:

func didPanMove(recongniser: UIPanGestureRecognizer){
    if((self.view.superview) != nil){
        if(recongniser.state == UIGestureRecognizerState.Began){
            // save the original position
            self._origPoint = self.view.frame.origin
        }
        // this is the translation of the last segment of the "move"
        let trans = recongniser.translationInView(self.view.superview!)
        // this is the velocity of the last segment of the "move"
        let velocity = recongniser.velocityInView(self.view.superview!)
    }
}

使用平移值来锻炼用户滑动的方向。不要忘记在每次调用 "didPanMove" 时添加 "trans" 值作为累积翻译。

您现在可以使用这些值来做很多事情。就像让出现的视图跟随手指的移动一样。或者当速度达到一定速度时,让视图 "snap" 到所需位置,就像滑动一样。也许如果用户滑动得不够快或不够远,让视图稍微跟随手指,然后 "snap" 在手势结束时回到隐藏位置。

要制作动画,如果您正在制作自定义滑出视图,您可能可以使用 UIView.animateWithDuration 为滑出视图制作动画。