SwiftUI:如何让 NavigationLink 不去任何地方并保持当前视图 [英] SwiftUI: How to make NavigationLink not go anywhere and stay on current view

查看:31
本文介绍了SwiftUI:如何让 NavigationLink 不去任何地方并保持当前视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在我的应用程序中进行一些表单验证,因此除非满足某些条件,否则我不希望导航链接转到指定的目的地.那么是否有可能以某种方式将目的地设置为 nil 或类似值,以便在按下导航链接时不满足条件时它会停留在当前视图上?

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?

推荐答案

改用 Button 并在验证后以编程方式激活隐藏的 NavigationLink.这是一个例子

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
    }
}

这篇关于SwiftUI:如何让 NavigationLink 不去任何地方并保持当前视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆