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

Activating a text field

Forums > 100 Days of SwiftUI

Hi,

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?

Thanks!

2      

@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.

2      

Thanks!

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)
                        .disableAutocorrection(true)
                        .focused($isFieldFocused)
                    Text("Your score is: \(userScore)")
                        .font(.title3.bold())

                }

        }
    }
    func addNewWord() {
        // code
        isFieldFocused = true
    }

2      

Thanks NigelGee, I'll check that out!

2      

Save 50% in my WWDC sale.

SAVE 50% To celebrate WWDC24, all our books and bundles are half price, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

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.