如何让 SwiftUI 中的选择器输出选择的值?
Posted
技术标签:
【中文标题】如何让 SwiftUI 中的选择器输出选择的值?【英文标题】:How to get the picker in SwiftUI to output the chosen value? 【发布时间】:2020-02-11 08:47:20 【问题描述】:我在 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[$0])")
.pickerStyle(SegmentedPickerStyle())
Section(header: Text("Result"))
Text("\(convertedValue)")
.navigationBarTitle("Convert It")
【问题讨论】:
【参考方案1】:试试这个。 (在您的文本中添加标签并使您的选择值成为 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")
【讨论】:
以上是关于如何让 SwiftUI 中的选择器输出选择的值?的主要内容,如果未能解决你的问题,请参考以下文章