iOS上的Xamarin.Forms中的动画TabbedPage过渡的滑动手势

时间:2017-12-01 04:59:52

标签: ios animation xamarin.forms gesture tabbedpage

在Xamarin.Forms中,在iOS上,如何扩展TabbedPage以便除了使用底部的标签更改页面外,用户还可以向左或向右滑动以更改页面?理想情况下,滑动时应该动画页面过渡。

页面中没有任何页面使用左手势或右手势,因此可以向左或向右滑动以明确指示更改当前页面的愿望。

1 个答案:

答案 0 :(得分:5)

以下代码响应用户滑动手势,其中使用交叉溶解动画的制表符更改。它为TabbedPage创建了一个自定义渲染器,为每个方向添加了一个iOS UISwipeGestureRecognizer

手势识别器与页面上的其他手势同时工作(否则,滚动等页面手势将阻止滑动手势工作,除非手势完全水平),但不是自身(否则,一次滑动将跨多个页面移动) )。

[assembly: ExportRenderer(typeof(TabbedPage), typeof(SwipeTabbedRenderer))]

class SwipeTabbedRenderer : TabbedRenderer
{
    public override void ViewWillAppear(bool animated)
    {
        base.ViewWillAppear(animated);

        NativeView.AddGestureRecognizer(new UISwipeGestureRecognizer(() => SelectNextTab(1)) { Direction = UISwipeGestureRecognizerDirection.Left, ShouldRecognizeSimultaneously = ShouldRecognizeSimultaneously });
        NativeView.AddGestureRecognizer(new UISwipeGestureRecognizer(() => SelectNextTab(-1)) { Direction = UISwipeGestureRecognizerDirection.Right, ShouldRecognizeSimultaneously = ShouldRecognizeSimultaneously });
    }

    void SelectNextTab(int direction)
    {
        int nextIndex = TabbedPage.GetIndex(Tabbed.CurrentPage) + direction;
        if (nextIndex < 0 || nextIndex >= Tabbed.Children.Count) return;
        var nextPage = Tabbed.Children[nextIndex];
        UIView.Transition(Platform.GetRenderer(Tabbed.CurrentPage).NativeView, Platform.GetRenderer(nextPage).NativeView, 0.15, UIViewAnimationOptions.TransitionCrossDissolve, null);
        Tabbed.CurrentPage = nextPage;
    }

    static bool ShouldRecognizeSimultaneously(UIGestureRecognizer gestureRecognizer, UIGestureRecognizer otherGestureRecognizer) => gestureRecognizer != otherGestureRecognizer;
}

改进的机会:幻灯片手势会比交叉消解更好,但当我尝试使用CATransition创建一个时,动画的初始状态是一个空白页,而不是起始标签页面。这导致动画有点刺耳。