我需要添加一个视图控制器作为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