Reputation: 11
I'm new with SwiftUI and I have a problem with the navigation with NavigationStack and .navigationDestination(). When I press the button with the label: Ir a binding View, the navigation doesn't occur. This is my code:
//
// StateView.swift
// SWiftUITutorial
//
// Created by Ismael Márquez on 10/4/24.
//
import SwiftUI
class UserData: ObservableObject {
@Published var name = "Ismael Márquez"
@Published var age = 22
}
struct StateView: View {
@State private var value = 0
@State private var selection: Int?
@State private var readyToNavigate = false
@StateObject private var user = UserData()
var body: some View {
NavigationStack {
VStack {
Text("El valor actual es \(value)")
Button("Suma 1") {
value += 1
}
Text("Mi nombre es \(user.name) y mi edad es \(user.age)")
Button("Actualizar datos") {
user.name = "Pedro"
user.age = 33
}
Button {
//Code here before changing the bool value
readyToNavigate = true
} label: {
Text("Ir a BindingView")
}
}
}.navigationTitle("StateView")
.navigationDestination(isPresented: $readyToNavigate) {
BindingView(value: $value, user: user)
}
}
}
#Preview {
StateView().environmentObject(UserData())
}
Previously I managed to do navigation with Navigation view and navigationLink but that method is deprecated in iOS 16.
Upvotes: 1
Views: 1608
Reputation: 358
I realize this isn't your exact problem but since I got here via google trying to solve the same thing, wanted to post in case someone else runs into the same problem I had. In my case, attaching the .navigationDestination to an if/else block didn't work consistently. I had to encapsulate everything into a Group and pin the .navigationDestination on the group, like this:
NavigationStack(path: $path) {
Group {
if homes.count < 1 {
...
} else {
...
}
}
.navigationDestination(for: NavigationItem.self) { item in ...
Upvotes: 1
Reputation: 700
Put the .navigationDestination()
in the NavigationStack:
NavigationStack {
VStack {
Text("El valor actual es \(value)")
Button("Suma 1") {
value += 1
}
Text("Mi nombre es \(user.name) y mi edad es \(user.age)")
Button("Actualizar datos") {
user.name = "Pedro"
user.age = 33
}
Button {
//Code here before changing the bool value
readyToNavigate = true
} label: {
Text("Ir a BindingView")
}
}.navigationDestination(isPresented: $readyToNavigate) {
BindingView(value: $value, user: user)
}
}.navigationTitle("StateView")
Upvotes: 2