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

SOLVED: How do I get @state field from an array back to update the original class that is defined in the calling view

Forums > SwiftUI

The array myScores in ContentView is passed up to the ScoreView view where each occurance is put into a textfield using the struct holeValue. How do I get those value back to the original array in the ContentView so the Button on that view would be a call to the database updating functions.

import SwiftUI

struct ContentView: View {
    var myScores = [scoreRec(Hole: 1, Score: 4),
                    scoreRec(Hole: 2, Score: 5),
                    scoreRec(Hole: 3, Score: 6),
                    scoreRec(Hole: 4, Score: 7),
                    scoreRec(Hole: 5, Score: 8),
                    scoreRec(Hole: 6, Score: 9),
                    scoreRec(Hole: 7, Score: 1),
                    scoreRec(Hole: 8, Score: 2)
    ]
    var body: some View {
        Button(action: { print("perform update with \(myScores[0].Score)") }) {
            Text("Update data base")
        }
        HStack {
            ScoreView(myScores: myScores)
        }
        .frame(width: 250, height: 81, alignment: .center)
    }
}
class scoreRec {
    internal init(Hole: Int, Score: Int) {
        self.Hole = Hole
        self.Score = Score
    }

    var Hole: Int
    var Score: Int

}
struct holeValue: View {

    @State  var score: String = ""
    var myScore: Int = 0
    init(_ scorerec: scoreRec) {
        self.myScore = scorerec.Score
    }

    var body: some View {
        TextField(String(myScore), text: self.$score)
            .onChange(of: score) {
                let txt = $0.filter("0123456789".contains)
                if let _ = Int(txt), txt.count <= 1 {
                    score = txt
                } else {
                    score = String(txt.dropLast())
                }

            }
    }

}
private struct ScoreView: View {

    var myScores:[scoreRec]

    var body: some View {
        HStack(spacing: 0) {
            Text("Score").frame(width: 45)

            ForEach(myScores, id: \.Hole) { scorerec in
                holeValue(scorerec)
                    .frame(width: 17)
                    .padding(3)
                    .border(Color.black)
                    .foregroundColor(.black)
            }

        }

    }
}
struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

The solution below got me done, I wound up passing in the array of $myScores with @binding in the holeView, then just updating the array in the .onChange as suggested.. Thanks so much...

3      

Firstly, you need to make your myScores variable an @State so that you can amend it

Then in your ScoreView struct, you mark myScores as @Binding then pass in $myScores from your contentView

then in your ForEach you can either use .indices and pass in the index like this:

 ForEach(myScores.indices, id: \.Hole) { scorerecIndex in
                holeValue(myScores[scorerecIndex], index:scorerecIndex)

or in your .onChange search in the array for the item you want to change.

Then finally modify the item in the array from within your .onChange

3      

you're very welcome glad it helped.

and yes, sorry I missed a step where the array needs passing into holeView as well.

I do sometimes wonder whether all this passing through multiple subviews is the right thing to do. I know theres environmentObject for use where a variable needs to be shared across miltiple views but that strikes me as more appropriate for use across the whole app rather than a view and it's subviews.

I should probably start a thread and ask that question rather than continue to wonder.

good luck with the rest of your project

all the best

Richard

3      

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.