我正在學習 MVVM 并將其應用于一個簡單的轉換器應用程式。當我嘗試使用 ForEach 將陣列傳遞到選擇器時,問題就出現了。這是我的代碼:
模型:
struct UserOptions {
var userOption = 0.0
var userChoseInput = "Meters"
var userChoseOutput = "Feets"
var userUnits = ["Meters", "Kilometers", "Feets", "Yards"]
}
視圖模型:
class ViewModel: ObservableObject {
@Published var options = UserOptions()
var finalResult: Double {...calculations here...}
}
看法:
struct ContentView: View {
@StateObject private var viewModel = RulerViewModel()
var body: some View {
Form {
Section {
Picker("What is your input?", selection: $viewModel.userChoseInput) {
ForEach($viewModel.userUnits, id: \.self) { _ in //Value of type 'ObservedObject<ViewModel>.Wrapper' has no dynamic member 'userUnits' using key path from root type 'ViewModel'
Text($viewModel.userChoseOutput)
}
}
.pickerStyle(.segmented)
} header: {
Text("Choose your input")
}
.textCase(nil)
Section {
TextField("Your number", value: $viewModel.userOption, format: .number)
.keyboardType(.decimalPad)
.focused($userValueIsFocused)
}
Section {
Picker("What is your output?", selection: $viewModel.userChoseOutput) {
ForEach($viewModel.userUnits, id: \.self) { _ in
Text(viewModel.userChoseOutput) //Value of type 'ObservedObject<ViewModel>.Wrapper' has no dynamic member 'userUnits' using key path from root type 'ViewModel'
}
}
.pickerStyle(.segmented)
}
uj5u.com熱心網友回復:
利用
$viewModel.options.userUnits
和
viewModel.options.userChoseOutput
至于你的回圈,這樣的事情會讓你訪問唯一的值
ForEach(viewModel.options.userUnits, id: \.self) { unit in
Text(unit)
}
我建議您也研究一下Measurement它會在處理轉換時為您節省大量時間。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/488284.html
下一篇:配置.htaccess
