UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Day 28 Picker can not change the View

Forums > 100 Days of SwiftUI

Hey guys.Today I try to change the betterRest but have shome problem. Here is my code. Anything helpful is very well.

when I changed Picker value there is no answer showed. But when I change the Stepper it will showed the answer.

//
//  ContentView.swift
//  Better Rest
//
//  Created by chen on 2022/1/27.
//

import CoreML
import SwiftUI

struct ContentView: View {

    @State private var wakeUP = defaultWakeTime
    @State private var sleepAmount = 8.0
    @State private var coffeeAmount = 1
    @State private var recommandWakeUpTime = ""
    //alert
    @State private var alertTitle = ""
    @State private var alertMessage = ""
    @State private var showingAlert = false

    static var defaultWakeTime:Date{
        var conponents = DateComponents()
        conponents.hour = 7
        conponents.minute = 0
        return Calendar.current.date(from: conponents) ?? Date.now
    }

    var body: some View {
        NavigationView{
            Form{
                Section{
                    Text("When do you want to wake Up?")
                        .font(.headline)

                    DatePicker("Please enter a time", selection: $wakeUP,displayedComponents: .hourAndMinute)
                        .labelsHidden()
                }
                Section{
                    Stepper("Sleep \(sleepAmount.formatted()) hours", value: $sleepAmount,in: 4...12,step: 0.25){ _ in calculateBedTime()}

                }
                Section{
                    Text("Daily coffee intake")
                    Picker("How many Cup of Coffee you drink", selection: $coffeeAmount) {
                        ForEach(1..<21) {
                            Button("\($0)", action: calculateBedTime)
                        }
                    }
                }
                Section{
                    Text("Recommand wakeUp Time is")
                    Text("\(recommandWakeUpTime)")
                        .font(.largeTitle)
                }
            }
            //    .navigationTitle("BetterRest")
//                .toolbar {
//                    Button("Calculator",action: calculateBedTime)
//                }
//                .alert(alertTitle, isPresented: $showingAlert) {
//                    Button("OK") { }
//                } message: {
//                    Text(alertMessage)
//                }
        }
    }
    func calculateBedTime(){
        do{
            let config = MLModelConfiguration()
            let model = try SleepCalculator(configuration: config)

            let componenets = Calendar.current.dateComponents([.hour, .minute], from: wakeUP)
            let hour = (componenets.hour ?? 0) * 60 * 60
            let minute = (componenets.minute ?? 0) * 60
            let prediction = try model.prediction(wake: Double(hour + minute), estimatedSleep: sleepAmount, coffee: Double(coffeeAmount))
            let sleepTime = wakeUP - prediction.actualSleep

            alertTitle = "Your ideal bedtime is…"
            alertMessage = sleepTime.formatted(date: .omitted, time: .shortened)
            recommandWakeUpTime = sleepTime.formatted(date: .omitted, time: .shortened)
            showingAlert = true
        }catch{
            alertTitle = "Error"
            alertMessage = "Sorry, there was a problem calculating your bedtime."
            showingAlert = true
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

3      

Try put a DatePicker with a default, like what you did with the wakeup time. Notice that you want the bedtime, not the wake-up time.

 @State private var idealBedTime = Date.now // this shows a default value of your idealBedTime.
 ...
                Section {
                    DatePicker("Please enter a time", selection: $idealBedTime, displayedComponents: .hourAndMinute).labelsHidden()
                } header: {
                    Text("Your ideal bedtime: ").font(.largeTitle)
                }
...
let idealBedTime = sleepTime //do this in your function

Right now you don't see anything before you hit the Stepper because your calculateBedTime() function is not triggered until you hit the Stepper. Since there is no default value there, you don't see anything displayed because calculation has not been executed yet.

1      

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.