SwiftUI
- Challenge day: Unit Converter
https://www.hackingwithswift.com/100/swiftui/19
I used VStack and HStack with the help of GPT-4.
import SwiftUI struct ContentView: View { @State private var f: Double = 68 @State private var c: Double = 0 @FocusState private var isFocusedF @FocusState private var isFocusedC func f2c(_ f: Double) -> Double { Double(String(format: "%.2f", (f-32) * 5 / 9))! } func c2f(_ c: Double) -> Double { Double(String(format:"%.2f", c * 9 / 5 + 32))! } var body: some View { NavigationStack { Form { Section("Temperature") { VStack(alignment: .leading) { HStack { TextField("F", value: $f, format: .number) .keyboardType(.numberPad) .onChange(of: f) { (oldValue, newValue) in if isFocusedF { self.c = f2c(newValue) } } .focused($isFocusedF) Text("°F").foregroundColor(.gray) } Divider().padding(.vertical) HStack { TextField("C", value: $c, format: .number) .keyboardType(.numberPad) .onChange(of: c) { (oldValue, newValue) in if isFocusedC { self.f = c2f(newValue) } } .focused($isFocusedC) Text("°C").foregroundColor(.gray) } .onAppear { self.c = f2c(f) } } .padding() } } .navigationTitle("Simple Metrics") } }
}
Screenshot: