BLACK FRIDAY SALE: Save 50% on all my Swift books and bundles! >>

Activating a text field

Forums > 100 Days of SwiftUI


Just finished the Word Scramble challenges, and was wondering how I can get the text field to a) Be automatically selected upon Restart Game b) Be automatically selected after pressing Return, so the user doesn't need to tap on the field each time.

If someone can point me in the right direction?



@randmtask looks for pointers.

If someone can point me in the right direction?

Since you're not providing code showing what you've tried, and you're just asking for pointers, start here in the forums!

At the top of the forum page, enter "focus" into the search bar.

You'll find several discussions about the .focus modifier. I think this will point you in the right direction.



That helps a lot.

I managed to get the field focused after each word by making isFieldFocused = true in the addNewWord() function.

But I'm unsure how I would have the field selected initially, if thats the behaviour I wanted. More a curiosity than anything!

struct ContentView: View {
    // code
    @FocusState private var isFieldFocused: Bool

    var body: some View {
        NavigationView {
            List {
                Section {
                    TextField("Enter your word", text: $newWord)
                        .autocapitalization(.none) // This will not capitalise the first word when the user types (although they still can if they want)
                    Text("Your score is: \(userScore)")


    func addNewWord() {
        // code
        isFieldFocused = true


Thanks NigelGee, I'll check that out!


Hacking with Swift is sponsored by Guardsquare

SPONSORED AppSweep by Guardsquare helps developers automate the mobile app security testing process with fast, free scans. By using AppSweep’s actionable recommendations, developers can improve the security posture of their apps in accordance with security standards like OWASP.

Learn more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

Unknown user

You are not logged in

Log in or create account

Link copied to your pasteboard.