![](/img/trans.png)
[英]Adding Subview To UIViewController Makes UITablview Subview Disappear
[英]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.