I found a very strange bug while using SwiftUI, and the following code is the minimum required to reproduce it.
When I press the 'Go to page2' button, the CPU load goes to 100% and the memory usage keeps increasing. What's wrong with this code?
I tried to search for a day but could not find any answer.
import SwiftUI
struct ContentView: View {
var body: some View {
NavigationStack {
Page1()
.environmentObject(Foo())
}
}
}
class Foo: ObservableObject {
init() {}
}
struct Page1: View {
u/EnvironmentObject
private var viewModel: Foo
u/Binding
var value: Int
init() {
self._value = .init(get: { 0 }, set: { _ in })
}
u/State
private var id: UUID? = nil
var body: some View {
NavigationLink(value: 0) {
Text("Go to page2")
.padding()
.foregroundStyle(.white)
.background(.black)
.cornerRadius(12)
}
.navigationDestination(for: Int.self) { _ in
Page2(
onComplete: {
print("value", value)
}
)
}
}
}
struct Page2: View {
public init(onComplete _: u/escaping () -> Void) {}
public var body: some View {
Text("This is Page2")
.task {
print("hi")
}
}
}
4
0
652