在移动到 destinationView 之前如何在 NavigationLink 中执行某些操作(例如:print("hi"))

Lal*_*lli 10 firebase swift swiftui

我正在尝试创建一个按钮,以便在导航到另一个视图之前执行一些操作。但是,如果我使用 Button,就无法导航到另一个视图,如果我使用 NavigationLink,除了导航之外,我什么也做不了。

我在下面添加按钮和导航链接。

我正在尝试使用此按钮进行 firebase 身份验证,在完成身份验证后,我想导航到另一个视图。

Button(action: {print("Hi")}) {
                Text("Create Account")
                    .font(.system(size: 20))
                    .foregroundColor(Color("GreyLabel0"))              
    }

NavigationLink(destination: WelcomeView()) {
     Text("Create Account")
                    .font(.system(size: 20))
                    .foregroundColor(Color("GreyLabel0"))
}
Run Code Online (Sandbox Code Playgroud)

kon*_*iki 8

在 beta 6 中,DynamicNavigationDestinationLink 消失了,所以我更新了答案以使用 NavigationLink。

请注意,目前 NavigationLink 中存在一个错误,请参见此处:https : //stackoverflow.com/a/57274613/7786555

import SwiftUI

struct ContentView: View {
    @State private var presentMe = false

    var body: some View {
        NavigationView {
            VStack {

                NavigationLink(destination: DetailView(), isActive: $presentMe) { EmptyView() }

                Button(action: {
                    print("hi")
                    self.presentMe = true
                }, label: {
                    Text("Present Now!")
                })

                Spacer()

            }.navigationBarTitle(Text("Top View"))
        }
    }
}

struct DetailView: View {
    var body: some View {
        Text("Detailed View")
    }
}
Run Code Online (Sandbox Code Playgroud)