簡體   English   中英

將其添加為子視圖后 Deinit UIViewController

[英]Deinit UIViewController after adding it as a subview

我需要添加一個視圖控制器作為 mt 當前視圖的子視圖,但在我不再需要它之后無法取消初始化

       let viewController = CountrySelectViewController()
        viewController.view.frame = self.view.bounds

        viewController.view.alpha=0

        self.view.addSubview(viewController.view)

        UIView.animate(withDuration: 0.25, delay: 0.0, options: [], animations: {
            viewController.view.alpha=1

        }, completion: { (finished: Bool) in
        })

        viewController.completionHandlerClose = {

            UIView.animate(withDuration: 0.25, delay: 0.0, options: [], animations: {
                viewController.view.alpha=0

            }, completion: { (finished: Bool) in

                viewController.view.removeFromSuperview()
                viewController.view = nil
            })

        }

有一個明顯的強引用循環,必須使用weak引用來打破:

viewController.completionHandlerClose = { [weak viewController] in
    guard let controller = viewController else { return }
    UIView.animate(
        withDuration: 0.25,
        delay: 0.0,
        options: [],
        animations: {
           controller.view.alpha = 0
        },
        completion: { _ in
            controller.view.removeFromSuperview()
            controller.view = nil
        }
    )
}

請參閱https://docs.swift.org/swift-book/LanguageGuide/AutomaticReferenceCounting.html

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM