首页 > 解决方案 > Swift UI 按钮动作函数

问题描述

我对 Swift 完全陌生,所以请原谅可能缺乏精确性。我正在尝试构建一个使用 REST API 进行身份验证的登录表单。这是我到目前为止遵循教程的内容。我的下一步是了解将提交表单的所有逻辑放在哪里。我想从它采用的内联方式中提取它。

我可以将函数传递给 action 参数吗?我尝试在 Xcode 上找到某种提取功能,但无法使其正常工作(它们是灰色的)。

import SwiftUI

let lightGreyColor = Color(red: 239.0/255.0, green: 243.0/255.0, blue: 244.0/255.0, opacity: 1.0)
let storedUsername = "john"
let storedPassword = "1234"

struct ContentView: View {
    @State var username: String = ""
    @State var password: String = ""
    @State var authenticationDidFail: Bool = false
    @State var authenticationDidSucceed: Bool = false
    
    
    var body: some View {
        ZStack {
            VStack {
                Image("logo")
                
                EmailField(username: $username)
                PasswordField(password: $password)
                if authenticationDidFail {
                    Text("Information not correct. Try again.")
                        .offset(y: -10)
                        .foregroundColor(.red)
                }
                Button(action: {
                    if  self.password == storedPassword {
                        print(password)
                        self.authenticationDidSucceed = true
                        self.authenticationDidFail = false
                    } else {
                        self.authenticationDidFail = true
                    }
                }) {
                    LoginButtonContent()
                }
                
                
            }
            if authenticationDidSucceed {
                Text("Login succeeded!")
            }
        }
        
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

struct LoginButtonContent: View {
    var body: some View {
        Text("LOGIN")
            .font(.headline)
            .foregroundColor(.white)
            .padding()
            .frame(width: 220, height: 60)
            .background(Color.green)
            .cornerRadius(15.0)
    }
}

struct PasswordField: View {
    @Binding var password: String
    
    
    var body: some View {
        SecureField("Password", text: $password)
            .padding()
            .background(lightGreyColor)
            .cornerRadius(5.0)
            .padding(.bottom, 20)
    }
}

struct EmailField: View {
    @Binding var username: String
    
    var body: some View {
        TextField("Username", text: $username)
            .padding()
            .cornerRadius(5.0)
            .padding(.bottom, 20)
    }
}

标签: swiftbuttonswiftui

解决方案


您可以在 Button 的操作中使用模型的对象,在那里您可以执行 REST 调用并返回结果以将值设置为 authenticationDidSucceed,以便更新 UI。

如果使用的类符合 ObservableObject 协议,您甚至可以使用其发布的变量来自动更新 UI。


推荐阅读