Learn SwiftUI (Day 19/100)

Learn SwiftUI (Day 19/100)

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") } }
}
Enter fullscreen mode
Exit fullscreen mode

Screenshot:

Image description


Discover more from Coursity

Subscribe to get the latest posts to your email.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *