Out of curiosity, have you tried using the Observable macro instead of the older ObservableObject?
Thank you for your response.
Using Observation, this issue no longer occurs.
Since this problem does not occur in iOS 17.x, it seems to be an issue with iOS 18.0 beta 2.
Additionally, as our product code needs to support iOS 15 and later, replacing Observation—which is only available from iOS 17—with Model and View code would lead to considerable duplication and make it difficult.
I also want to share that I was able to reproduce the issue with the following code, which does not use ObservableObject or Observation.
import SwiftUI
enum Kind { case none, a, b, c }
// Selection is storing the selected values in the NavigationStack.
struct Selection: Hashable, Identifiable {
let id = UUID()
let num: Int
init(num: Int) {
self.num = num
print("id: \(id), num: \(num)")
}
}
// Data is corresponding to the selection.
struct Data {
let data: Int
}
@main
struct iOS16_4NavigationSampleApp: App {
var body: some Scene {
WindowGroup {
RootView()
}
}
}
struct RootView: View {
var body: some View {
if #available(iOS 16.0, *) {
NavigationStack {
NavigationLink {
ContentView()
} label: {
Text("album")
}
}
} else {
EmptyView()
}
}
}
struct ContentView: View {
@State var kind: Kind = .a
@State var vals: [Selection] = {
return (1...5).map { Selection(num: $0) }
}()
@State var selection: Selection?
@Environment(\.dismiss) private var dismiss
var body: some View {
list
.onChange(of: self.selection) { newValue in
print("changed: \(String(describing: newValue?.num))")
}
}
@ViewBuilder
private var list: some View {
if #available(iOS 16.0, *) {
List(selection: $selection) {
ForEach(self.vals) { val in
NavigationLink(value: val) {
Text("\(String(describing: val))")
}
}
}
.navigationDestination(isPresented: .init(get: {
return selection != nil
}, set: { newValue in
if !newValue {
selection = nil
}
}), destination: {
SubView(kind: .a)
})
}
}
}
//
struct SubView: View {
init(kind: Kind) {
}
init() {
}
var body: some View {
Text("Content")
}
}
Topic:
UI Frameworks
SubTopic:
SwiftUI
Tags: