Search code examples
c#xamarinxamarin.iosmvvmcross

How to use UIViewControllerTransitioningDelegate with MvxIosViewPresenter?


I have a view controller A and a view controller B and I want to navigate from A to B (present modally) with a custom transition (UIViewControllerTransitioningDelegate), how would I do it with MvxIosViewPresenter?

Do I need to write a completely custom presenter by myself or is there a way how to do in an elegant way?


Solution

  • it is completely possible to use a custom transition with the MvxIosViewPresenter. All you have to do is to create a custom UIViewControllerTransitioningDelegate and assign it to your ViewController (ViewDidLoad is a good place to do it).

    Something like this should do the work:

    [MvxModalPresentation(ModalPresentationStyle = UIModalPresentationStyle.OverFullScreen, ModalTransitionStyle = UIModalTransitionStyle.CrossDissolve)]
    public partial class ModalView : MvxViewController<ModalViewModel>
    {
        public ModalView(IntPtr handle) : base(handle)
        {
        }
    
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();
    
            TransitioningDelegate = new TransitioningDelegate();
        }
    }
    
    public class TransitioningDelegate : UIViewControllerTransitioningDelegate
    {
        public override IUIViewControllerAnimatedTransitioning GetAnimationControllerForPresentedController(UIViewController presented, UIViewController presenting, UIViewController source)
        {
            return new CustomTransitionAnimator();
        }
    }
    
    public class CustomTransitionAnimator : UIViewControllerAnimatedTransitioning
    {
        public override double TransitionDuration(IUIViewControllerContextTransitioning transitionContext)
        {
            return 1.0f;
        }
    
        public override void AnimateTransition(IUIViewControllerContextTransitioning transitionContext)
        {
            var inView = transitionContext.ContainerView;
            var toVC = transitionContext.GetViewControllerForKey(UITransitionContext.ToViewControllerKey);
            var toView = toVC.View;
    
            inView.AddSubview(toView);
    
            var frame = toView.Frame;
            toView.Frame = CGRect.Empty;
    
            UIView.Animate(TransitionDuration(transitionContext), () =>
            {
                toView.Frame = new CGRect(10, 10, frame.Width - 20, frame.Height - 20);
            }, () =>
            {
                transitionContext.CompleteTransition(true);
            });
        }
    

    }