Search code examples
swiftuipicker

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


I have a picker in swiftUI that are used to show Units of Measure and convert between them. The picker is displayed correctly, but the values are not selected when choosing one of them.

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[$0])")
                        }
                    }
                    .pickerStyle(SegmentedPickerStyle())
                }
                                
                Section(header: Text("Result")) {
                    Text("\(convertedValue)")
                }
                
            }
        .navigationBarTitle("Convert It")
        }
    }
}


Solution

  • try this. (added tags to your text and made your selection value an 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")
        }
    }
    }