NavigationStack 与 .navigationDestination 不适合我

问题描述 投票:0回答:1

我是 SwiftUI 新手,我在使用 NavigationStack 和 .navigationDestination() 进行导航时遇到问题。当我按下带有标签的按钮:Ir a Binding View 时,不会发生导航。这是我的代码:

//
//  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())
}

之前我成功地使用导航视图和navigationLink进行导航,但该方法在iOS 16中已被弃用。

swift xcode swiftui swiftui-navigationlink swiftui-navigationstack
1个回答
0
投票

.navigationDestination()
放入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")
© www.soinside.com 2019 - 2024. All rights reserved.