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

User Input into Arrays in SwiftUI

Forums > SwiftUI

I have been trying to write code to enable a user to input integer data into an Array, I am struggling with what should be a simple operation.

The Array is an EnvironmentObject comprised of 20 Integers.

I would like the User to the prompted to enter integer data for each item in the Array, from a single view within the App.

Can anyone assist with the code for this, or point me to where I can learn this?

Thanks.

2      

You can try something like this:

import SwiftUI

class InputFields: ObservableObject {
    @Published var inputs: [Int] =  Array(repeating: 0, count: 20)
}

struct TwentyInputView: View {
    //keep track of the Int values in the environment
    @EnvironmentObject var fields: InputFields

    //keep track of the current String values of our 20 text fields locally
    @State private var inputs: [String] = Array(repeating: "", count: 20)

    var body: some View {
        VStack {
            ForEach(fields.inputs.indices) { idx in
                TextField("Field \(idx)", text: $inputs[idx])
                    .keyboardType(.numberPad)
                    .onChange(of: inputs[idx]) { value in
                        //the value we get in is a String, so we need to
                        //convert it to an Int before we update the
                        //EnvironmentObject fields
                        fields.inputs[idx] = Int(value) ?? 0
                    }
            }
            .onAppear {
                //load our EnvironmentObjects fields into the
                //local state and convert from String -> Int
                fields.inputs.indices.forEach { idx in
                    inputs[idx] = String(fields.inputs[idx])
                }
            }
        }
    }
}

struct TwentyInputView_Previews: PreviewProvider {
    static var previews: some View {
        TwentyInputView()
    }
}

3      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

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.