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

SOLVED: TextFields - How to move to the first one?

Forums > SwiftUI

Wrote some code with TextFields and can't figure out when finished entering in each how to go back to the first one.

For example you have a TextField for first name, last name and age. When finished with entering in age how do you have the cursor go back into the TextField for first name?

import SwiftUI

struct ContentView: View {

@State private var firstName = ""
@State private var lastName = ""
@State private var age = ""

@State private var fullName: [String] = []

var body: some View {
    Form {
        TextField("First name", text: $firstName)
        TextField("Last name", text: $lastName)
        TextField("Age", text: $age)

        padding()

        Button {
            save()
        } label: {
            Text("Save")
                .padding()
                .frame(maxWidth: .infinity)
                .foregroundColor(.black)
                .background(.red.opacity(0.7))
                .cornerRadius(40)
        }

        ForEach(fullName, id:\.self) { data in
            Text(data)
        }
    }
}

func save() {
    fullName.append(firstName + " " + lastName + " - " + age)
    firstName = ""
    lastName = ""
    age = ""
}

}

2      

Using your code in the simulator, when you click on Save, the first field is automatically selected.

Also if you want to go any particular field, just select using the mouse. Alternatively, use Shift + Tab to move to the previous field.

So is that what you wanted to know?

2      

When you click "Save" the 3 TextFields clear out and it adds it and prints the array but the cursor remains in the last TextField. Here it isn't an issue as there are only 3 TextFields but what happens if you have 10-12 all in different Sections. How to reset so you go back to the first one or selected one?

2      

Add a enum of

enum Field: Hashable {
    case firstName, lastName, age
}

Then add

 @FocusState private var focus: Field?

then use

TextField("First name", text: $firstName)
        .focused($focus, equals: .firstName)

and add this to the method

focus = .firstName

So should be like this

struct ContentView: View {
    enum Field: Hashable {
        case firstName, lastName, age
    }

    @State private var firstName = ""
    @State private var lastName = ""
    @State private var age = ""
    @FocusState private var focus: Field?

    @State private var fullNames: [String] = []

    var body: some View {
        Form {
            TextField("First name", text: $firstName)
                .focused($focus, equals: .firstName)

            TextField("Last name", text: $lastName)
                .focused($focus, equals: .lastName)

            TextField("Age", text: $age)
                .focused($focus, equals: .age)

            Button {
                save()
            } label: {
                Text("Save")
                    .padding()
                    .frame(maxWidth: .infinity)
                    .foregroundColor(.black)
                    .background(.red.opacity(0.7))
                    .cornerRadius(40)
            }

            ForEach(fullNames, id:\.self) { fullName in
                Text(fullName)
            }
        }
    }

    func save() {
        fullNames.append(firstName + " " + lastName + " - " + age)
        firstName = ""
        lastName = ""
        age = ""
        focus = .firstName
    }
}

you can now jump to any field.

PS arrays are usally named as purals eg fullNames so when you do the ForEach you can use the single fullName

3      

You can add the following properties

    @State private var showingAlert = false
    @State private var message = ""

and add an alert to the Form

.alert("Incomplete entry", isPresented: $showingAlert) { } message: { Text(message) }

You can then change the method to this

func save() {
    if firstName.isEmpty {
        message = "You need to enter a given name!"
        showingAlert.toggle()
        focus = .firstName
    } else if lastName.isEmpty {
        message = "You need to enter a family name!"
        showingAlert.toggle()
        focus = .lastName
    } else if age.isEmpty {
        message = "You need to enter a age!"
        showingAlert.toggle()
        focus = .age
    } else {
        fullNames.append(firstName + " " + lastName + " - " + age)
        firstName = ""
        lastName = ""
        age = ""
        focus = .firstName
    }
}

Now if they miss one of the fields then cursor will be in that field

2      

Thank you!!!

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!

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.