swift - 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)
}
}
解决方案
您可以在 Button 的操作中使用模型的对象,在那里您可以执行 REST 调用并返回结果以将值设置为 authenticationDidSucceed,以便更新 UI。
如果使用的类符合 ObservableObject 协议,您甚至可以使用其发布的变量来自动更新 UI。
推荐阅读
- testing - 在页面模型中将参数传递给 TestCafe 选择器
- java - 在全屏启动器应用程序来自后台后,Android NFC 读取失败
- python - 将文件从一个文件夹复制到另一个在 .txt 文件中具有匹配名称的文件夹
- intellij-idea - 是否可以防止 Intellij 自动导入整个类包?
- oracle - 我如何从 TRIGGER 解决 Oracle 突变错误
- python - 出现错误类型错误:“int”和“str”实例之间不支持“>”,
- django - 如何在 http 栏中显示类别?
- reactjs - 我在以下 react-redux 代码中遇到初始化错误
- python - 在大多数情况下,VADER polar_scores 将输出返回为“中性”
- json - 如何使用 django rest 框架修改多对多集合