这就是崩溃的样子
所以它在 UIKit 线上随机崩溃
UIKitCore
-[UIViewController _ancestorViewControllerOfClass:allowModalParent:] + 44
我在默认的 SwiftUI 导航堆栈中有视图:
struct MyView: View {
@EnvironmentObject var viewModel: MyViewModel
@Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>
var body: some View {
ZStack {
......
}
.onAppear {
self.viewModel
.onViewAppear(presentationMode: self.presentationMode)
}
}
}
final class MyViewModel {
var presentationMode: Binding<PresentationMode>?
func onViewAppear(presentationMode: Binding<PresentationMode>) {
self.presentationMode = presentationMode
}
func hide() {
presentationMode?.wrappedValue.dismiss() // crashes after calling this
}
}
所以我以这种方式将 MyView 推送到导航堆栈中:
NavigationLink(
destination: MyView()
) {
Image(systemName: "plus.circle")
.font(.title)
}
然后在用户在几秒钟后按下 MyView 中的按钮后,我调用hide()
MyViewModel。几乎所有时间它都在工作,但在 5-10% 的情况下它会崩溃。