我想等到关闭动画完成,但我不想在我的代码中使用很多块,所以我用 UIViewController
extension
编写了这个函数(几乎就像几年前对我来说一样):
func dismissAnimated() {
var comleted: Bool = false
self.dismiss(animated: true) {
comleted = true
}
while !comleted {
RunLoop.current.run(mode: RunLoop.Mode.common, before: Date.distantFuture)
}
}
所以现在而不是:
viewController.dismiss(animated: true) {
// code after completion
}
我应该写:
viewController.dismissAnimated()
// code after completion
但它不会关闭视图控制器,也不会进入完成块。
我尝试了不同的RunLoop模式,尝试了不同的日期,尝试将RunLoop.current.run插入while条件,但它不起作用。任何想法如何实现这一目标?
编辑:
它适用于iOS 9或类似的东西(可能有一些代码更改,因为我找不到我的源代码)。我开始RunLoop.current.run
以避免阻塞主线程。例如,如果我completed = true
放在 DispatchQue.main.asyncAfter 中,它将起作用,问题出在dismiss
我再次尝试是因为我很好奇,这个解决方案实际上对我有用:
@objc private func dismissTapped() {
let dismissalTime = dismissAnimated()
print("Dismissal took: %ld", abs(dismissalTime))
}
private func dismissAnimated() -> TimeInterval {
let startDate = Date()
var completed = false
self.dismiss(animated: true) {
completed = true
}
while !completed {
RunLoop.current.run(mode: .default, before: .distantFuture)
}
return startDate.timeIntervalSinceNow
}
iOS 12.1.2 |Swift 4.2
它不会关闭,因为您的while !completed
循环已使主线程停止,并且 UI 更新发生在主线程上。在dismiss
完成闭包中运行您需要运行的任何代码有什么问题?
self.dismiss(animated: true) {
runSomeCode()
}
如果真的只是不使用块,也许这可能是一个解决方案?
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
if self.navigationController?.isBeingDismissed ?? self.isBeingDismissed {
print("Dismissal completed...")
}
}