Reading values from list of toggles in SwiftUI

我是研究僧i 提交于 2020-04-17 07:17:49

问题


I hope this question isn't too stupid. I'm stuck with this problem for a long time now, tried different approaches and I'm still failing. I'm quite new to Swift and SwiftUI, that's why maybe I don't see the obvious.

I have a View which contains of a List of toggles. The toggle list relies on setData which is built from a JSON-file which contains an id, a name and an imageUrl. In this view the user is able to select different sets to start a game with:

import SwiftUI

struct GameGenerationView: View {
    var body: some View {
        VStack {
            List(setData, id: \.id) { set in
                GameGenerationRow(set: set, store: SetSelectionStore(id: set.id, name: set.name))

            }
            Button(action: {
                print("results")

            }) {
                Text("Spiel starten")
            }
        }
        .navigationBarTitle("Spielgenerator", displayMode: .inline)
    }
}

struct GameGenerationView_Previews: PreviewProvider {
    static var previews: some View {
        GameGenerationView()
    }
}

Secondly there is the actual Toggle GameGenerationRow:

import SwiftUI

struct GameGenerationRow: View {
    var set: CardSet
    @ObservedObject var store: SetSelectionStore

    var body: some View {
        HStack {
            Toggle(isOn: $store.selection) {
                Spacer()
                Text(set.name)
                    .fontWeight(.bold)
            }
            .frame(height: 35)
        }
    }

}

struct GameGenerationRow_Previews: PreviewProvider {
    static var previews: some View {
        GameGenerationRow(set: setData[0], store: SetSelectionStore(id: 1, name: "test"))
    }
}

The data of each Toggle is collected in my SetSelectionStore:

import SwiftUI
import Combine

final class SetSelectionStore: ObservableObject {
    var id: Int
    var name: String
    @Published var selection: Bool = false

    init(id: Int, name: String) {
        self.id = id
        self.name = name
    }

    func returnStore() -> [String:Any] {
        return [
            "id": self.id,
            "name": self.name,
            "selection": self.selection
        ]
    }
}

After pressing the button in the GameGenerationView I want to collect the states from the toggles like this...

[
 {
   name: "Set1"
   usedForGame: 0
 },
 {
   name: "Set2"
   useForGame: "1"
 }
]

... in order to pass it to a function to select the game data and navigate to a new view.

I googled a lot and I was not able to find a solution for collection the states for the different toggles. Is there an easy way to do so? Did I choose a whole wrong approach? Hopefully somebody can help out and push me into the right direction.

Thank you!

来源:https://stackoverflow.com/questions/60836499/reading-values-from-list-of-toggles-in-swiftui

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!