如何让SwiftUI中的选择器输出选择的值?

How to get the picker in SwiftUI to output the chosen value?

我在 swiftUI 中有一个选择器,用于显示度量单位并在它们之间进行转换。选择器显示正确,但选择其中一个值时未选择值。

import SwiftUI

struct ContentView: View {
    
    @State private var originalValue  = ""
    @State private var originalUnit = ""
    @State private var convertedUnit = ""
    
    let lenghtUnits = ["meters", "miles", "yards"]
    
    var convertedValue : Double {
      return 0 // for now..
    }
    
    var body: some View {
        NavigationView {
            Form {
                Section(header: Text("From:")) {
                    
                    TextField("Value:", text: $originalValue)
                        .keyboardType(.decimalPad)
                    
                    Picker("fromUnit" , selection: $originalUnit) {
                        ForEach(0 ..< lenghtUnits.count) {
                            Text("\(self.lenghtUnits[[=10=]])")
                        }
                    }
                    .pickerStyle(SegmentedPickerStyle())
                }
                                
                Section(header: Text("Result")) {
                    Text("\(convertedValue)")
                }
                
            }
        .navigationBarTitle("Convert It")
        }
    }
}

试试这个。 (将标签添加到您的文本并将您的选择值设为 int)

struct ContentView: View {

@State private var originalValue  = ""
@State private var originalUnit = 0
@State private var convertedUnit = ""

let lenghtUnits = ["meters", "miles", "yards"]

var convertedValue : Double {
  return 0 // for now..
}

var body: some View {
    NavigationView {
        Form {
            Section(header: Text("From:")) {

                TextField("Value:", text: $originalValue)
                    .keyboardType(.decimalPad)

                Picker("fromUnit" , selection: $originalUnit) {
                    ForEach(0 ..< lenghtUnits.count) { index in
                        Text("\(self.lenghtUnits[index])").tag(index)
                    }
                }
                .pickerStyle(SegmentedPickerStyle())
            }

            Section(header: Text("Result")) {
                Text("\(convertedValue)")
            }

        }
    .navigationBarTitle("Convert It")
    }
}
}