GO FURTHER, FASTER: Try the Swift Career Accelerator today! >>

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 Essential Developer.

SPONSORED Transform your career with the iOS Lead Essentials. Unlock over 40 hours of expert training, mentorship, and community support to secure your place among the best devs. Click for early access to this limited offer and a FREE crash course.

Click to save your free spot now

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

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.