double - SwiftUI Picker,将 String 转换为 Double
问题描述
我正在使用 SwiftUI 并有一个 Picker 选择数组中的一些字符串,这些字符串是数字。选择器运行良好,我可以在屏幕上显示值,但是我需要能够将数组中的选定字符串设置为双倍的。
我敢肯定有一些非常善良和聪明的人可以帮助我。
我想设置:
var totalFrequency : 双 = 0.0
来自 Picker 的两个值。
谢谢 !!!
克雷格
import SwiftUI
struct DipoleSelect : View {
@State var mhzValueIndex = 0
@State var mhzValueStepIndex = 0
var frequencyValue = ["1", "2", "3", "4", "5", "6", "7", "8", "9" ]
var frequencyStep = [".000", ".005", ".010"]
var totalFrequency : Double = 0.0
var body: some View {
VStack {
Text("Select Frequency")
.font(.largeTitle)
.fontWeight(.heavy)
.padding([.top,], -180.0)
Picker(selection: $mhzValueIndex, label: Text("")) {
ForEach(0 ..< frequencyValue.count) {
Text(self.frequencyValue[$0] + " mhz").font(.largeTitle).fontWeight(.semibold).color(Color.black).tag($0)
}.font(.title)
}.padding(.top, -170)
Picker(selection: $mhzValueStepIndex, label: Text("")) {
ForEach(0 ..< frequencyStep.count) {
Text(self.frequencyStep[$0]).tag($0)
}
}.padding()
Text("You Selected \(frequencyValue[mhzValueIndex])\(frequencyStep[mhzValueStepIndex]) Mhz")
}
}
}
解决方案
我想出了这个解决方案。希望它对你有用。
final class Property: BindableObject {
var didChange = PassthroughSubject<Property, Never>()
var frequencyValue = ["1", "2", "3", "4", "5", "6", "7", "8", "9" ]
var frequencyStep = [".000", ".005", ".010"]
var mhzValueIndex: Int = 0 {
didSet{
totalFrequency = totalFrequency + getDouble(value: frequencyValue[mhzValueIndex])
didChange.send(self)
}
}
var mhzValueStepIndex: Int = 0 {
didSet {
totalFrequency = totalFrequency + getDouble(value: frequencyStep[mhzValueStepIndex])
didChange.send(self)
}
}
var totalFrequency: Double = 0.0 {
didSet{
didChange.send(self)
}
}
func getDouble(value: String) -> Double {
return Double(value)!
}
}
struct DipoleSelect : View {
@EnvironmentObject var property: Property
var body: some View {
VStack {
Text("Select Frequency")
.font(.largeTitle)
.fontWeight(.heavy)
.padding()
Picker(selection: $property.mhzValueIndex, label: Text("")) {
ForEach(0 ..< property.frequencyValue.count) {
Text(self.property.frequencyValue[$0] + " mhz").font(.largeTitle).fontWeight(.semibold).color(Color.black).tag($0)
}.font(.title)
}
Picker(selection: $property.mhzValueStepIndex, label: Text("")) {
ForEach(0 ..< property.frequencyStep.count) {
Text(self.property.frequencyStep[$0]).tag($0)
}
}
Text("You Selected \(property.frequencyValue[property.mhzValueIndex])\(property.frequencyStep[property.mhzValueStepIndex]) Mhz")
Text("Total frequency: \(property.totalFrequency)")
}
}
}
推荐阅读
- python-3.x - 当我们在sql中使用sum语句时,如何删除python中返回的十进制字符串?
- reactjs - Fetch 没有设置 cookie
- django - 不同型号的 M2M 订购列表?
- sas - SAS:日期间隔,包括几个月的 15 日
- laravel - 如何在 laravel 中获取更新的记录 ID?
- javascript - JS 闭包上下文对象的寿命?
- mysql - /etc/init.d/ 目录中缺少 mysql
- visual-studio-code - 具有排除和包含 glob 模式的扩展激活
- reactjs - 向 URL 添加额外的查询参数后,React 组件状态清除
- database - 如何使用firebase在xamarin中指定当前的关键节点?