SwiftUI在表单选择器中传递键和值

时间:2019-11-04 21:56:24

标签: swift dictionary swiftui

  

我在哪里可以将我的值传递给更新我的barChart而不是   按键更新barChart。我希望选择器仍在选择器标签上显示键   但是我想通过scoreModel.eventMDL.values更新的条形图   scoreModel是一个字典事件MDL = [Double:Double,]

class UpdateScoreBar: ObservableObject {
        @Published var rawScoreMDL = 0.0
    }

> This is the main view that passes in RawScoreView

    struct ScoreCalcView: View {
        @ObservedObject private var updateScoreBar = UpdateScoreBar()

        var body: some View {
            ZStack {
                Color("appBackround").edgesIgnoringSafeArea(.all)
                VStack {
                    RawScoreView()
                }.animation(.default)
            }
        }
    }
    struct ScoreBarView: View {


> This is the initial value for the barChart

        var value: CGFloat = 0

        var body: some View {
            VStack{
                ZStack (alignment: .bottom) {
                    Capsule().frame(width: 34, height: 200)
                        .foregroundColor(Color("barColorBackround"))
                    Capsule().frame(width: 34, height: value)
                        .foregroundColor(Color.red)
                    Capsule().frame(width: 30, height: value)
                        .foregroundColor(Color("barColorForeground"))
                }
            }
        }
    }
    struct RawScoreView: View {
        @ObservedObject private var updateScoreBar = UpdateScoreBar()
        @ObservedObject private var scoreModel = ScoreModel()

        var body: some View {
            VStack {
                HStack {

>  updates the view, here is where im trying to pass in the
> scoreModel.eventMDL.values

                    ScoreBarView(value: CGFloat(updateScoreBar.rawScoreMDL))
                }
                NavigationView {
                    Form {
                        Section {

> this binds the selection and updates the view

                            Picker(selection: $updateScoreBar.rawScoreMDL, label: Text("3-Rep Max Deadlift")) {
                                List(self.scoreModel.eventMDL.keys.sorted().reversed(), id: \.self) { i in
                                    Text("\(i, specifier: "%g") Lbs.")
                                }
                            }
                        }
                    }.navigationBarTitle(Text("Raw Score"), displayMode: .inline)
                }
            }
        }
    }

1 个答案:

答案 0 :(得分:0)

我认为您需要更改以获取所需的唯一东西是:

ScoreBarView(value: CGFloat(scoreModel.eventMDL[updateScoreBar.rawScoreMDL] ?? 0))

Picker的绑定将更新updateScoreBar.rawScoreMDL,您可以使用该键在scoreModel.eventMDL词典中查找相应的值。尽管永远不要设为nil,但我们提供了默认值0,以防万一,将其转换为CGFloat并将其传递给ScoreBarView。由于rawScoreMDL@Published变量,因此,每当您进行新选择时,分数栏都会自动更新。