1

I'm working on a project that will need to do calculations based on the user's age.

I'm wanting to start completely with SwiftUI and I can do the graphical stuff but I'm at a loss as to how to use that information.

So the standard code I have is this:

struct ContentView: View {
    
    @State private var birthDate = Date()
    
    var body: some View{
        Form {
            DatePicker("Birth date:", selection: $birthDate, in: ...Date(), displayedComponents: .date).datePickerStyle(WheelDatePickerStyle()).font(.title)
        }
    }
}

What I'm having trouble with is how do I take the information from the date picker to then calculate the age of the user to store in a variable for later calculations?

Thanks so much for any help you can provide.

  • Does this answer your question? [Calculate age from birth date using NSDateComponents in Swift](https://stackoverflow.com/questions/25232009/calculate-age-from-birth-date-using-nsdatecomponents-in-swift) – Andrew Feb 20 '21 at 08:26
  • Does NSDateComponents work in iOS and macOS? I'm looking at developing universal apps so if it's one or the other then it's not going to work for me. However if it works on both then I've misunderstood and skipped over this because of wrong thinking. – Loweded Wookie Feb 20 '21 at 08:42
  • It is now DateComponents, it will work on both. See the Apple Docs for more info https://developer.apple.com/documentation/foundation/datecomponents – Andrew Feb 20 '21 at 14:38

1 Answers1

1

You can use .onChange to track the changes in birthDate and do the calculation inside the closure.

Note: SwiftUI runs this closure in main thread. so If you want to do expensive work there you should dispatch to a background Queue to let the UI run smoothly.

struct ContentView: View {
    
    @State private var birthDate = Date()
    @State private var age: DateComponents = DateComponents()
    
    var body: some View{
        VStack {
            Form {
                DatePicker("Birth date:", selection: $birthDate, in: ...Date(), displayedComponents: .date).datePickerStyle(WheelDatePickerStyle()).font(.title)
            }.onChange(of: birthDate, perform: { value in
                age = Calendar.current.dateComponents([.year, .month, .day], from: birthDate, to: Date())
        })
            Text("Age-> Years:\(age.year ?? 0) Months:\(age.month ?? 0) Days\(age.day ?? 0)")
        }
    }
}

YodagamaHeshan
  • 4,996
  • 2
  • 26
  • 36