Swiftui Navigationview Trying to Pop to Missing Destination (Monoceros)

SwiftUI NavigationView pop itself when a datasource is finished loading

This happens because you're specifying id as item itself, and when list updated there's no original item anymore, so it closes

If you just wanna modify items without adding/removing/reordering, you can make index your item id:

NavigationView {
List(viewModel.dataSource.indices, id: \.self) { i in
let item = viewModel.dataSource[i]
NavigationLink(destination: Text("\(item)")) {
Text("\(item)")
.padding()
}
}
}

But with more complex data you need to have your items Identifiable with unique ids, and you won't have such problem. Check out this example:

struct ContentView: View {
@ObservedObject var viewModel = ViewModel()

var body: some View {
NavigationView {
List(viewModel.dataSource) { item in
NavigationLink(destination: Text("\(item.value)")) {
Text("\(item.value)")
.padding()
}
}
}
}
}

class ViewModel: ObservableObject {
@Published private(set) var dataSource: [Item] = [1, 2, 3, 4, 5]

init() {
DispatchQueue.main.asyncAfter(deadline: .now() + 3) { [self] in // simulate calling webservice
// you're modifying value but id stays the same
self.dataSource[0].value = 99
}
}
}

struct Item: Identifiable, ExpressibleByIntegerLiteral {
let id = UUID()
var value: Int

init(integerLiteral value: IntegerLiteralType) {
self.value = value
}
}

NavigationLink within view presented as an overlay. SwiftUI

Your NavigationLink is not inside the NavigationView! Try this:

struct ContentView: View {

var body: some View {
NavigationView {
Color.clear
.overlay(
VStack {
NavigationLink(destination: Text("Go to some view")) {
Text("NavigationLink in overlay")
}
Button {
print("button tapped")
} label: {
Text("Button in overlay")
}
}
)
}
}
}


Related Topics



Leave a reply



Submit