Xcode Version 13.2.1 (13C100)
iOS15.2
Swift5
If repeat the navigation about 10 times, it will return FirstView automatically.
The expected output is to move from 0 to 100 with the next button.
I am developing a list navigation app with SwiftUI. A navigation bug occurred in the code and procedure shown below.
1.tap item in FirstView.
2.open SecondView.
3.open ThirdView.
4.tap next button navigate to SecondView.
Repeat steps 2-4 about 10 times navigate SecondView when pop View to FirstView.
How can I solve it?
import SwiftUI
final class ViewModel: ObservableObject {
@Published var currentIndex: Int?
public func next() {
if let currentIndex = self.currentIndex {
if currentIndex < 100 {
self.currentIndex = currentIndex + 1
} else {
self.currentIndex = nil
}
}
}
}
struct FirstView: View {
@StateObject var vm = ViewModel()
var body: some View {
NavigationView {
List(0..<100) { i in
NavigationLink(String(i),
tag: i,
selection: $vm.currentIndex) {
SecondView(vm: vm)
}.isDetailLink(false)
}
}
.navigationViewStyle(StackNavigationViewStyle())
.navigationTitle("First View")
}
}
struct SecondView: View {
@ObservedObject var vm: ViewModel
var body: some View {
VStack {
NavigationLink("go to third") {
ThirdView(vm: vm)
}.isDetailLink(false)
if let currentIndex = vm.currentIndex {
Text("currentIndex: \(currentIndex)")
}
}
.navigationTitle("Second View")
}
}
struct ThirdView: View {
@ObservedObject var vm: ViewModel
var body: some View {
VStack {
Button(action: vm.next) {
Text("next")
}
if let currentIndex = vm.currentIndex {
Text("currentIndex: \(currentIndex)")
}
}
.navigationTitle("Third View")
}
}
Post
Replies
Boosts
Views
Activity
SwiftUI Preview Don't work.
Progress Preparing iPhone Simulator for Previews.
SwiftUI
Xcode version 13.0
macOS Big Sur version 11.6