SwiftUI_visionOS_Note

@FocusState

May 8, 2024
1 min read|

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.

Setup

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)
    }
}
swift

There’s no systematic way to click the textfield other than clicking the text field.

FocuseState

@FocusState private var usernameInFocus: Bool
swift

We create a boolean of usernameInFocus

TextField(...)
	.focused($usernameInFocus)
swift

We bind the variable with the TextField, so whenever the text field is triggered, the boolean value switches.

Button to switch the FocusState

            Button("Toggle") {
                usernameInFocus.toggle()
            }
swift

by adding a toggle function to switch the boolean value, now we can open up the keyboard by clicking the button.

Showing keyboard by .onAppear

.onAppear{
	DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
		self.usernameInFocus = true
		}
}
swift

Means, after 0.5 seconds, usernameInFocus turns to true

Change the focus state

Button("sign up"){
	let usernameIsValid = !username.isEmpty
	let passwordIsValid = !password.isEmpty
}
swift

constant usernameIsValid is not empty (!username.isEmpty)

Button("sign up"){
	let usernameIsValid = !username.isEmpty
	let passwordIsValid = !password.isEmpty
	
	if usernameIsValid && passwordIsValid {
		print("SIGN UP")
	}
}
swift

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
	}
}
swift

if only the username isn’t empty, open the password, and vice versa

Subscribe to our newsletter

Get the latest news and updates from our team