1

以下代码重现了该错误:

import SwiftUI

struct ContentView: View {
    @State private var number: Int = 5
    var body: some View {
        NavigationView() {
            VStack(spacing: 20) {
                NavigationLink(destination: SecondView(bottles: $number)) {
                    Text("Click me")
                }
            }
        }
    }
}

struct SecondView: View {
    @Environment(\.presentationMode) private var presentationMode: Binding<PresentationMode>
    @State private var color: UIColor = .black
    @Binding var bottles: Int

    var body: some View {
        Text("I have \(bottles) in my bag")
            .foregroundColor(Color(color))
            .navigationBarTitle(Text("Water Bottle"))
            .navigationBarItems(trailing:
                Button("Click") {
                    self.someFunction()
                }
        )
    }

    func someFunction() {
        if self.color == UIColor.black {
            self.color = .red
        } else {
            self.color = .black
        }
    }
}

从 SecondView 滑回 ContentView 但未完成手势时,应用程序冻结。删除 @Environment 或 NavigationBarItem 时将修复此错误。

对于@Environment,CoreData 需要它,但使用presentationMode 来重现错误

4

1 回答 1

2

将“.navigationViewStyle(StackNavigationViewStyle())”添加到 NavigationView 为我解决了这个问题。这是我用于在真实设备(iPhone、iPad)和各种模拟器上测试的代码。使用 macos 10.15.5、Xcode 11.5 和 11.6 beta,目标 ios 13.5 和 mac 催化剂。

我尚未在所有设备上对此进行测试,因此如果您发现无法使用此功能的设备,请告诉我。

import SwiftUI

struct ContentView: View {
@State private var number: Int = 5
var body: some View {
    NavigationView() {
        VStack(spacing: 20) {
            NavigationLink(destination: SecondView(bottles: $number)) {
                Text("Click me")
            }
        }
    }.navigationViewStyle(StackNavigationViewStyle())  //  <---
}
}

struct SecondView: View {
@Environment(\.presentationMode) private var presentationMode: Binding<PresentationMode>
@State private var color: UIColor = .black
@Binding var bottles: Int

var body: some View {
    Text("I have \(bottles) in my bag")
        .foregroundColor(Color(color))
        .navigationBarTitle(Text("Water Bottle"))
        .navigationBarItems(trailing:
            Button("Click") {
                self.someFunction()
            }
    )
}

func someFunction() {
    if self.color == UIColor.black {
        self.color = .red
    } else {
        self.color = .black
    }
}
}
于 2020-06-13T02:46:47.187 回答