繁体   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