NEW: My new book Pro SwiftUI is out now – level up your SwiftUI skills today! >>

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 Judo

SPONSORED Let’s face it, SwiftUI previews are limited, slow, and painful. Judo takes a different approach to building visually—think Interface Builder for SwiftUI. Build your interface in a completely visual canvas, then drag and drop into your Xcode project and wire up button clicks to custom code. Download the Mac App and start your free trial today!

Try now

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.