본문 바로가기
IT/swift

100 days of SwiftUI - Day28

by 가능성1g 2024. 11. 24.
반응형

어제의 프로그램을 조금더 개선? 수정? 하는 내용이다. 

 

위의주석에 나와있는것처럼

1. VStack -> Section 으로 변경하기

2. Stepper -> Picker 변경하기

3. 상단 계산버튼 제거하고 아래에 크게 결과 나타내기 이다.

/*
1. Replace each VStack in our form with a Section, where the text view is the title of the section. Do you prefer this layout or the VStack layout? It’s your app – you choose!
2. Replace the “Number of cups” stepper with a Picker showing the same range of values.
3. Change the user interface so that it always shows their recommended bedtime using a nice and large font. You should be able to remove the “Calculate” button entirely.
*/

//
//  ContentView.swift
//  BetterRest
//
//  Created by HanTJ on 11/23/24.
//

import SwiftUI
import CoreML

struct ContentView: View {
    @State private var wakeUp = defaultWakeTime
    @State private var sleepAmount = 8.0
    @State private var coffeeAmount = 1
    
    @State private var alertTitle = ""
    @State private var alertMessage = ""
    @State private var showingAlert = false
    
    @State private var yourBetterRest = ""
    
    static var defaultWakeTime: Date {
        var components = DateComponents()
        components.hour = 7
        components.minute = 0
        return Calendar.current.date(from: components) ?? .now
    }
    
    var body: some View {
        NavigationStack{
            Form {
                Section {
                    Text("언제 일어나고 싶나요?")
                        .font(.headline)
                    
                    DatePicker("시간을 입력하세요", selection: $wakeUp, displayedComponents: .hourAndMinute)
                        .labelsHidden()
                }
                
                Section {
                    Text("자고싶은 수면의 시간")
                        .font(.headline)
                    
                    Stepper("\(sleepAmount.formatted()) 시간", value: $sleepAmount, in: 4...12, step: 0.25)
                }
                
                Section {
                    Text("하루에 먹는 커피양")
                        .font(.headline)
                    
                    //Stepper("\(coffeeAmount) 잔", value: $coffeeAmount, in: 1...20)
                    Picker("커피 잔 수", selection: $coffeeAmount) {
                        ForEach(1...10, id: \.self ) {
                            Text("\($0)").tag($0)
                        }
                    }
                }
                
                Section {
                    Button("알고싶다!"){
                        calculateBedTime()
                    }
                    .frame(width: 200)
                    .frame(maxWidth: .infinity, alignment: .center)
                    
                    Text("\(yourBetterRest)")
                        .font(.largeTitle)
                }
            }
            .navigationTitle("더 나은 숙면을 위하여")
            .alert(alertTitle, isPresented: $showingAlert) {
                Button("OK") { }
            } message: {
                Text(alertMessage)
            }
            /*
            .toolbar {
                Button("계산", action: calculateBedTime)
            }
             */
        }
    }
    
    func calculateBedTime() {
        do {
            let config = MLModelConfiguration()
            let model = try SleepCalculator(configuration: config)
            
            let components = Calendar.current.dateComponents([.hour, .minute], from: wakeUp)
            let hour = (components.hour ?? 0) * 60 * 60
            let minute = (components.minute ?? 0) * 60
            
            let prediction = try model.prediction(wake: Double(hour+minute), estimatedSleep: sleepAmount, coffee: Double(coffeeAmount))
            
            let sleepTime = wakeUp - prediction.actualSleep
            
            alertTitle = "잠자리에 들어야 하는시간은…"
            alertMessage = sleepTime.formatted(date: .omitted, time: .shortened)
            
            yourBetterRest = alertMessage + " 자라!"
        }catch {
            alertTitle = "오류"
            alertMessage = "숙면시간 계산중 오류 발생"
        }
        //showingAlert = true
    }
}

#Preview {
    ContentView()
}

더 나아진건진 모르겠지만!

 

어쨌든 깔끔쓰!!

반응형