[swift] 모달 뷰에 애니메이션 효과를 추가하는 방법은?

애플리케이션에 모달 뷰를 추가할 때 애니메이션 효과를 적용하려면 UIViewControllerTransitioningDelegate 프로토콜을 채택하고 해당 뷰 컨트롤러를 프레젠테이션하는 데 사용되는 트랜지션 애니메이션을 정의해야 합니다. 여기에 필요한 단계를 살펴보겠습니다.

1. Transitioning Delegate 구현

우선, 모달 뷰를 띄울 뷰 컨트롤러에 UIViewControllerTransitioningDelegate 프로토콜을 채택하여, 해당 뷰 컨트롤러의 프레젠테이션 스타일과 트랜지션 애니메이션을 제어하는 메서드를 구현합니다.

class YourViewController: UIViewController, UIViewControllerTransitioningDelegate {
    // ...
    
    func presentationController(forPresented presented: UIViewController, presenting: UIViewController?, source: UIViewController) -> UIPresentationController? {
        return YourCustomPresentationController(presentedViewController: presented, presenting: presenting)
    }
    
    // ...
}

2. Presentation Controller 구현

이어서, 커스텀 프레젠테이션 컨트롤러를 정의하고 모달 뷰의 프레젠테이션에 대한 레이아웃 및 애니메이션 동작을 구현합니다.

class YourCustomPresentationController: UIPresentationController {
    // ...
    
    override func presentationTransitionWillBegin() {
        // Add custom animation for presentation transition
    }
    
    override func dismissalTransitionWillBegin() {
        // Add custom animation for dismissal transition
    }
    
    // ...
}

3. 애니메이션 추가

presentationTransitionWillBegindismissalTransitionWillBegin 메서드 내에서, 모달 뷰의 프레젠테이션 및 해제에 대한 애니메이션 효과를 정의합니다. 이를 통해 모달 뷰가 나타나거나 사라질 때 원하는 애니메이션을 구현할 수 있습니다.

4. 모달 뷰 호출

마지막으로, 모달 뷰를 호출할 때 해당 뷰 컨트롤러의 modalPresentationStyle.custom으로 설정하고 modalPresentationStyletransitioningDelegate를 설정하여 커스텀 프레젠테이션 및 애니메이션을 적용합니다.

let modalViewController = YourModalViewController()
modalViewController.modalPresentationStyle = .custom
modalViewController.transitioningDelegate = self
present(modalViewController, animated: true, completion: nil)

위의 단계를 따르면 모달 뷰에 커스텀 애니메이션 효과를 쉽게 추가할 수 있습니다. ※ 참고 자료: Apple Developer Documentation - Custom View Controller Presentations and Transitions

적용하는 애니메이션의 유형에 따라 작성해야 할 코드가 달라질 수 있으므로, 해당 부분에 유의하여 각각의 애니메이션 효과에 맞게 코드를 구현해주시기 바랍니다.