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
Rxswift: Observable While a Button Holds Down
Uitableviewcell Asynchronously Loading Images Issue - Swift
Swift 2.0 Constraintswithvisualformat
Can You Use String/Character Literals Within Swift String Interpolation
iOS - Arkit Node Disappear After 100M
Swift Package Manager - Swift 4 Syntax
Change What Print(Object) Displays in Swift 2.0
Create Instance of Class Known at Runtime in Swift
Skaction Runaction Does Not Execute Completion Block
Swift Generics: Cannot Convert Value of Type to Expected Argument Type
Executefetchrequest Doesn't Return the Nsmanagedobject Subclass
Swiftui: How Do Style Text View with Different Font and Colour on String Subranges
How to Sort Objects by Its Enum Value
Swift .Uppercasestring or .Lowercasestring Property Replacement
Seeking an "Exit" Equivalent in Swift
Swift: Switch Between Nsviewcontroller Inside Container View/Nsview