这篇文章介绍了 SwiftUI 中的挑战 4-3,睡眠时间预测应用的开发过程。作者通过将 VStack 表单中的每个替换为 Section,并用 Picker 显示相同数值范围的“杯数”步进器,改进了用户界面。同时,作者还分享了在项目开发过程中遇到的困难和解决方法。
此内容根据文章生成,并经过人工审核,仅用于文章内容的解释与总结
投诉挑战
- 将VStack表单中的每个替换为Section,其中文本视图是该部分的标题。你喜欢此布局还是该VStack布局?这是你的应用-你可以选择!
- 用Picker显示相同数值范围的“杯数”步进器代替。
- 更改用户界面,以使其始终使用漂亮的大字体显示建议的就寝时间。你应该可以完全删除“计算”按钮。
遇到的困难
ForEach数字循环需要从0开始
ForEach中第1个变量可以用 $0
代替
在此项目情境下,使用do
catch
组合时,return
要放在do
catch
内。
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
| import SwiftUI
struct ContentView: View { @State private var sleepAmount = 8.0 @State private var wakeUp = Date() @State private var coffeePicker = 0 @State private var coffeeAmount = 1 @State private var alertTitle = "" @State private var alertMessage = "" @State private var showingAlert = false var body: some View { NavigationView { Form { Section(header: Text("When do you want to wake up?")) { DatePicker(selection: $wakeUp,displayedComponents: .hourAndMinute, label: { Text("Please enter a date") }) .labelsHidden() } Section(header: Text("Desired amount of sleep")) { Stepper(value: $sleepAmount, in: 4...12, step: 0.25) { Text("\(sleepAmount, specifier: "%g") hours") } } Section (header: Text("Daily coffee intake")) { Picker(selection: $coffeePicker, label: Text("Daily coffee intake")) { ForEach (0 ..< 20){ if $0 == 0 { Text("1 cup") }else{ Text("\(Int($0 + 1)) cups") } } } } Section(header: Text("Your ideal bedtime is")){ Text(sleeptime()) .font(.largeTitle) .fontWeight(.bold) .foregroundColor(Color.blue) .frame(maxWidth: .infinity) } } .navigationBarTitle("BetterRest") .alert(isPresented: $showingAlert){ Alert(--- title: Text(alertTitle), message: Text(alertMessage), dismissButton: .default(Text("OK"))) } } } func sleeptime() -> String { let model = SleepCalculator() let components = Calendar.current.dateComponents([.hour, .minute], from: wakeUp) let hour = (components.hour ?? 0) * 60 * 60 let minute = (components.minute ?? 0) * 60 do { coffeeAmount = coffeePicker + 1 let prediction = try model.prediction(wake: Double(hour + minute), estimatedSleep: sleepAmount, coffee: Double(coffeeAmount)) let sleepTime = wakeUp - prediction.actualSleep let formatter = DateFormatter() formatter.timeStyle = .short alertMessage = formatter.string(from: sleepTime) alertTitle = "Your ideal bedtime is ..." return formatter.string(from: sleepTime) } catch { alertTitle = "Error" alertMessage = "Sorry there was a problem calculating your bedtime." showingAlert = true return "Error" } } }
|
参考资料
查看下一天的SwiftUI学习笔记
关于100days英文课程