【问题标题】:Navigate to new screen on button click SwiftUI在按钮单击 SwiftUI 时导航到新屏幕
【发布时间】:2019-11-18 10:40:51
【问题描述】:

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

        }
    }

【问题讨论】:

    标签: swiftui


    【解决方案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
        }
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-11-23
      • 2023-03-04
      • 2023-01-26
      • 2019-12-15
      • 2019-09-25
      • 2018-07-17
      • 1970-01-01
      相关资源
      最近更新 更多