Как сделать анимацию перехода между ViewController в Swift?

Пользователь

от hattie , в категории: Swift , 6 месяцев назад

Как сделать анимацию перехода между ViewController в Swift?

Facebook Vk Ok Twitter LinkedIn Telegram Whatsapp

1 ответ

Пользователь

от cooper.berge , месяц назад

@hattie 

В Swift для создания анимации перехода между UIViewController можно использовать несколько подходов. Один из популярных подходов — это использование пользовательских переходов с помощью UIViewControllerAnimatedTransitioning и UIViewControllerTransitioningDelegate. В этом примере я покажу, как создать простой анимированный переход между двумя контроллерами.

1. Настройте первый UIViewController

Предположим, у вас есть FirstViewController, и вы хотите перейти на SecondViewController.

2. Создайте класс для анимации перехода

Создайте класс, который будет реализовывать протокол UIViewControllerAnimatedTransitioning.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import UIKit

class CustomTransitionAnimator: NSObject, UIViewControllerAnimatedTransitioning {
    let duration = 0.5

    func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
        return duration
    }

    func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
        guard let fromView = transitionContext.view(forKey: .from),
              let toView = transitionContext.view(forKey: .to) else {
            return
        }
        
        let containerView = transitionContext.containerView
        containerView.addSubview(toView)

        toView.alpha = 0.0
        UIView.animate(withDuration: duration, animations: {
            toView.alpha = 1.0
            fromView.alpha = 0.0
        }) { finished in
            fromView.alpha = 1.0
            transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
        }
    }
}


3. Реализуйте UIViewControllerTransitioningDelegate в первом контроллере

Ваш контроллер должен реализовывать протокол UIViewControllerTransitioningDelegate, чтобы указать, какой класс будет заниматься анимацией перехода.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
class FirstViewController: UIViewController, UIViewControllerTransitioningDelegate {
    override func viewDidLoad() {
        super.viewDidLoad()
    }

    @IBAction func presentSecondViewController() {
        let secondViewController = SecondViewController()
        secondViewController.transitioningDelegate = self
        secondViewController.modalPresentationStyle = .fullScreen
        self.present(secondViewController, animated: true, completion: nil)
    }

    // MARK: - UIViewControllerTransitioningDelegate

    func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        return CustomTransitionAnimator()
    }

    func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        return CustomTransitionAnimator()
    }
}


4. Настройте второй UIViewController

В SecondViewController вы можете добавить кнопку или жест для возврата к FirstViewController.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class SecondViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white

        let dismissButton = UIButton(type: .system)
        dismissButton.setTitle("Dismiss", for: .normal)
        dismissButton.addTarget(self, action: #selector(dismissVC), for: .touchUpInside)

        dismissButton.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(dismissButton)
        NSLayoutConstraint.activate([
            dismissButton.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            dismissButton.centerYAnchor.constraint(equalTo: view.centerYAnchor)
        ])
    }

    @objc func dismissVC() {
        self.dismiss(animated: true, completion: nil)
    }
}


Теперь, когда вы нажимаете кнопку на вашем первом контроллере, SecondViewController будет представлен с кастомной анимацией перехода, а затем вы сможете закрыть его также с анимацией.