导航到按钮单击SwiftUI的新屏幕

时间:2019-11-18 10:40:51

标签: swiftui

我有一个登录屏幕,希望在单击“登录”按钮时导航到新屏幕。 我确实尝试将按钮和整个屏幕布局包装在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 个答案:

答案 0 :(得分:0)

这是可行的方法

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
    }
})
相关问题