swift - 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)
}
}
}
}
解决方案
我认为你唯一需要改变以获得你想要的东西是:
ScoreBarView(value: CGFloat(scoreModel.eventMDL[updateScoreBar.rawScoreMDL] ?? 0))
的Picker
绑定将更新updateScoreBar.rawScoreMDL
,您使用该键在scoreModel.eventMDL
字典中查找相应的值。虽然它不应该是nil
,但我们提供了一个默认值 0,以防万一,转换为 CGFloat,并将其传递给ScoreBarView
. 因为rawScoreMDL
是一个@Published
变量,所以每当您进行新选择时,得分栏都会自动更新。
推荐阅读
- angular - 如何从 Angular 中的异步输入中获取“就绪”值
- android - 使用 takeUntil 和 debounce 进行递归调用
- c - OpenCV Tiff 错误的颜色值读数
- python - 不鼓励在测试模块中导入 conftest.py 吗?
- html - 如何将 img 放置在高度由 flexbox 计算的元素内,以使该元素的高度不会改变
- ruby-on-rails - rails 将字符串内的字符串分组
- statistics - 给定总体均值、标准差和样本量,如何求样本均值的方差
- drupal-8 - 防止从 url drupal 8 直接访问 .htaccess 和 web.config
- android - Android:将所有视图设置为可见以进行测试/调试
- javascript - 清除或重新启动异步功能