[英]SwiftUI passing keys and values in Form Picker
我在哪里可以将我的值传递给更新我的 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)
}
}
}
}
我认为你唯一需要改变以获得你想要的东西是:
ScoreBarView(value: CGFloat(scoreModel.eventMDL[updateScoreBar.rawScoreMDL] ?? 0))
Picker
的绑定将更新updateScoreBar.rawScoreMDL
,您可以使用该键在scoreModel.eventMDL
字典中查找相应的值。 虽然它不应该是nil
,但我们提供了一个默认值 0,以防万一,转换为 CGFloat,并将其传递给ScoreBarView
。 因为rawScoreMDL
是一个@Published
变量,所以每当您进行新选择时,得分栏都会自动更新。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.