首页 > 解决方案 > SwiftUI 在表单选择器中传递键和值

问题描述

我在哪里可以将我的值传递给更新我的 barChart 而不是更新 barChart 的键。我希望 Picker 仍然在 Picker Label 上显示键,但是我想通过 scoreModel.eventMDL.values 更新 barChart scoreModel 是字典 eventMDL = [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)
                }
            }
        }
    }

标签: swiftdictionaryswiftui

解决方案


我认为你唯一需要改变以获得你想要的东西是:

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

Picker绑定将更新updateScoreBar.rawScoreMDL,您使用该键在scoreModel.eventMDL字典中查找相应的值。虽然它不应该是nil,但我们提供了一个默认值 0,以防万一,转换为 CGFloat,并将其传递给ScoreBarView. 因为rawScoreMDL是一个@Published变量,所以每当您进行新选择时,得分栏都会自动更新。


推荐阅读