在SwiftUI中,点击按钮后导航到新屏幕

3

我有一个登录界面,希望在点击“登录”按钮时导航到新的界面。 我尝试将按钮和整个屏幕布局包裹在NavigationView下,并嵌入了一个Navigation Link中。 我不知道如何在按钮被点击时显示新的界面。以下是登录界面的代码。

ZStack {
        Color.red
            .edgesIgnoringSafeArea(.all)


        VStack(alignment: .center, spacing: 180.0) {
            Text("SwiftUI")
            .font(.largeTitle)
            .bold()
            .padding()

            VStack(alignment: .center, spacing: 25) {
                TextField("Username", text: $userName)
                    .padding(.all)
                    .background(Color.white)
                    .cornerRadius(10)

                TextField("Password", text: $userPassword)
                    .padding(.all)
                    .background(Color.white)
                .cornerRadius(10)

                Toggle(isOn: $isFirstTimeUser) {
                    Text("First Time User")
                        .font(.headline)
                        .bold()
                        .padding(.horizontal, -10)
                        .foregroundColor(Color.white)
                }.padding(.horizontal, 17)

                Button(action: {
                    if self.userName.count <= 5 {
                        self.isAlertShown = true
                    } else {


                    }
                })
                    {
                        Text(isFirstTimeUser ? "SignUp" : "Login")
                            .fontWeight(.medium)
                            .font(.title)
                            .foregroundColor(Color.red)
                            .padding(.horizontal, 10)
                    }.padding()
                .background(Color.white)
                .cornerRadius(10)
                    .alert(isPresented: $isAlertShown) {
                        () -> Alert in
                        Alert(title: Text("UserName Invalid"), message: Text("Username has to be more than 5 characters"), dismissButton:.default(Text("Got that!")))
                    }
            }.padding(.horizontal, 17)

        }
    }
1个回答

1

这里有一个可能的方法:

1)在您的视图中添加链接标签状态变量

@State private var current: Int? = nil

2) 将您的视图层次结构包装到 NavigationView 中,以使可能的 NavigationLink 起作用

3) 在您的按钮上方添加标记的 NavigationLink

NavigationLink(destination: YourDestinationViewHere(), tag: 1, selection: $current) {
    EmptyView()
}

4) 将链接标签选择添加到按钮操作中

Button(action: {
    if self.userName.count <= 5 {
        self.isAlertShown = true
    } else {
        self.current = 1 // this activates NavigationLink with specified tag
    }
})

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接