Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI: How to make NavigationLink not go anywhere and stay on current view

I am doing a bit of form validation in my app, and so I dont want the navigation link to go to the specified destination unless certain conditions are met. So is it possible to somehow set the destination to nil or similar so that it stays on the current view if conditions are not met when the navigation link is pressed?

like image 798
WY34 Avatar asked Oct 16 '25 02:10

WY34


1 Answers

Use Button instead and activate hidden NavigationLink programmatically if validated. Here is an example

struct DemoView: View {
    @State private var isValid = false

    var body: some View {
        NavigationView {
            Button("Validate") {
                // some validate code here like
                self.isValid = self.validate()
            }
            .background(
                NavigationLink(destination: Text("Destination"), isActive: $isValid) { EmptyView() }
            )
        }
    }
    
    private func validate() -> Bool {
        return true
    }
}
like image 171
Asperi Avatar answered Oct 17 '25 16:10

Asperi