개발하는 동글 :]

[TIL],[UIKit],[화면 dismiss후 present] 본문

카테고리 없음

[TIL],[UIKit],[화면 dismiss후 present]

동글하다 2023. 10. 19. 21:58

1. 왜 dismiss후 present 가 필요 할까?

지금 구현한 LockScreen ViewController는 비밀번호가 일치 할 때 TargetViewController를 띄워주는 기능을 하고 있다. 이렇게 작동하게 될 때 NavigationController에 쌓이는 컨트롤러는 아래와 같다 여기서 문제가 발생하였다. LockScreen ViewController는 메모리에 올라와있어 불필요한 메모리와 이 후 뷰에서 접근이 가능한 상태가 되는 문제가 발생한다

그렇기에 비밀번호가 일치해서 다음 화면으로 넘어갈 때 LockScreenViewController를 dismiss한 후 targetViewController를 present하는 방법이 필요하다.

2. 어떠한 방법으로 해결할 수 있을까?

2.1 dissmiss의 completion 사용

let rootView = presentingViewController

self.dismiss(animated: false, completion: {
    let vc = TargetViewController()
    rootView?.present(vc, animated: true, completion: nil)
 })
이러한 방법은 NavigationController로 화면을 관리할 수 없어서 이 방법을 선택할 수 없다.

2.2 NavigationController의 메서드를 extension

NavigationController를 확장하여 pop,push ViewController 메서드에 completion 핸들러를 추가하자.
extension UINavigationController {
    func popViewController(animated: Bool, completion: @escaping () -> Void) {
        CATransaction.setCompletionBlock(completion)
        CATransaction.begin()
        _ = self.popViewController(animated: animated)
        CATransaction.commit()
    }
    
    func pushViewController(_ viewController: UIViewController, animated: Bool, completion: @escaping () -> Void) {
        CATransaction.setCompletionBlock(completion)
        CATransaction.begin()
        self.pushViewController(viewController, animated: animated)
        CATransaction.commit()
    }
}
그 후 completion 핸들러를 이용하여 dissmiss한 후 present를 하자
print("[LockScreenViewController]: 비밀번호 일치")
                    self.navigationController?.popViewController(animated: false, completion: {
                        let vc = self.viewModel.targetViewController
                        self.viewModel.rootViewController.navigationController?.pushViewController(vc, animated: true)
                    })

3. Refernce

https://zartt.tistory.com/5