如何在SwiftUI中将测量值与UI绑定?

4

我想创建一个简单的转换器。 有没有可能将Measurement()与UI绑定? 错误显示必须将Measurement绑定为一个字符串。 提前感谢您! 以下是代码:

import SwiftUI
struct ContentView: View {
    @State private var tCelsius = Measurement(value: 0, unit: UnitTemperature.celsius)

    var fromCelsiusToFahrenheit: Measurement<UnitTemperature> {
        tCelsius.converted(to: .fahrenheit)
    }

    var body: some View {

        NavigationView {
            Form {
                TextField("Type the temperature", text: $tCelsius)
                Text("\(fromCelsiusToFahrenheit)")
            }

        }
    }
}

看一下MeasurementFormatter,它可以将测量值转换为可显示的字符串。 - rraphael
2个回答

1
你需要创建一个定制的绑定,将你的测量值转换为字符串
你可以通过在temperatureBinding的getter中使用MeasurementFormatter来改进下面的代码。
struct ContentView: View {
    @State private var tCelsius = Measurement(value: 0, unit: UnitTemperature.celsius)

    var fromCelsiusToFahrenheit: Measurement<UnitTemperature> {
        tCelsius.converted(to: .fahrenheit)
    }

    var body: some View {

        let temperatureBinding = Binding<String>(
            get: { self.tCelsius.description },
            set: { temperatureString in
                guard let newTemperature = Double(temperatureString) else { return }
                self.tCelsius.value = newTemperature
            }
        )

        return NavigationView {
            Form {
                TextField("Type the temperature", text: temperatureBinding)
                Text("\(fromCelsiusToFahrenheit)")
            }

        }
    }
}

-1

是的,您需要使用其中一个值格式化程序构造函数,如下所示:

@State var min: Measurement<UnitMass> = Measurement(value: 0, unit: .pounds)

private var massFormatter = MeasurementFormatter()

var body: some View {
    TextField("Min", value: $min, 
                     formatter: massFormatter).keyboardType(.decimalPad)
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接