I completely new on Swift, so excuse possible lack of precision. I am trying to build a login form that authenticates with a REST API. Here is what I have so far following this tutorial. My next step is understanding where to put all of the logic for submitting the form. I would like to extract it from the inline manner it is taking.
Can I pass a function to the action parameter? I tried finding some sort of extract feature on Xcode but couldn't get it to work (they are greyed).
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)
}
}