UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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      

Hacking with Swift is sponsored by RevenueCat

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

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.