In practice, this will most often be associated with users clicking on TextFields. In this video, we will first learn what Focus State is and then review a few real-world implementations! As a bonus, we will also check out Apple's documentation on this new feature.
struct ContentView: View {
@State private var username: String = ""
var body: some View {
VStack{
TextField("Add youe name here", text: $username)
.padding(.leading)
.frame(height: 55)
.frame(maxWidth: .infinity)
.background(.black.opacity(0.15))
.clipShape(RoundedRectangle(cornerSize: CGSize(width: 25, height: 25)))
}.padding(40)
}
}
There’s no systematic way to click the textfield other than clicking the text field.
@FocusState private var usernameInFocus: Bool
We create a boolean of usernameInFocus
TextField(...)
.focused($usernameInFocus)
We bind the variable with the TextField, so whenever the text field is triggered, the boolean value switches.
Button("Toggle") {
usernameInFocus.toggle()
}
by adding a toggle function to switch the boolean value, now we can open up the keyboard by clicking the button.
.onAppear{
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
self.usernameInFocus = true
}
}
Means, after 0.5 seconds, usernameInFocus
turns to true
Button("sign up"){
let usernameIsValid = !username.isEmpty
let passwordIsValid = !password.isEmpty
}
constant usernameIsValid
is not empty (!username.isEmpty
)
Button("sign up"){
let usernameIsValid = !username.isEmpty
let passwordIsValid = !password.isEmpty
if usernameIsValid && passwordIsValid {
print("SIGN UP")
}
}
if those two constants are true (constants aren’t empty), then print “SIGN UP”)
Button("sign up"){
let usernameIsValid = !username.isEmpty
let passwordIsValid = !password.isEmpty
if usernameIsValid && passwordIsValid {
print("SIGN UP")
} else if usernameIsValid {
usernameInFocus = false
passwordInFocus = true
} else {
usernameInFocus = true
passwordInFocus = false
}
}
if only the username isn’t empty, open the password, and vice versa