@countermind works really well, and I will add a bit more especially for the newer SwiftUI user like myself.
I created a MyButton and having the distance as an @ObservedObject for reactivity.
class MyDistance: ObservableObject {
@Published var distance: Measurement<UnitLength>
init() {
distance = Measurement<UnitLength>(value: 13.37, unit: .meters)
}
}
struct ContentView: View {
@StateObject var distance = MyDistance()
var body: some View {
VStack {
Text("\(distance.distance.formatted(.measurement(width: .abbreviated, usage: .asProvided, numberFormatStyle: .number)))")
MyButton(distance: distance)
}
.frame(minWidth: 300)
.padding()
}
}
struct MyButton: View {
// for reactivity.
@ObservedObject var distance: MyDistance
var body: some View {
Button("Convert to km") { print("Convert to km");
distance.distance = distance.distance.converted(to: .kilometers)
}
}
}
Topic:
App & System Services
SubTopic:
General
Tags: