Boo*_* PT 5 ios swift swiftui ios-navigationview property-wrapper
以下代码重现了该错误:
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
}
}
}
Run Code Online (Sandbox Code Playgroud)
当从 SecondView 滑回 ContentView 但未完成手势时,应用程序会冻结。删除@Environment或NavigationBarItem时将修复此错误。
对于@Environment,CoreData需要它,但使用presentationMode来重现错误
将“.navigationViewStyle(StackNavigationViewStyle())”添加到NavigationView可以解决我的问题。这是我在真实设备(iPhone、iPad)和各种模拟器上测试的代码。使用 macos 10.15.5、Xcode 11.5 和 11.6 beta,目标 ios 13.5 和 mac Catalyst。
我尚未在所有设备上对此进行测试,因此如果您发现此功能不起作用的设备,请告诉我。
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
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2484 次 |
| 最近记录: |