我想在一天中的不同时间显示不同的视图。
ContentView2()
从 12:30 到 15:00。
ContentView3()
从 15:00 到 18:30。
这里的问题是,当它是 15:30 时,将打开 ContentView2() 而不是 ContentView3()。
let dateComps = Calendar.current.dateComponents([.hour, .minute], from: Date())
struct MainViewa: View {
var body: some View {
if (dateComps.hour! >= 12 && dateComps.minute! >= 30) && dateComps.hour! <= 15 {
ContentView2()
} else if dateComps.hour! >= 15 && (dateComps.hour! <= 18 && dateComps.minute! <= 30) {
ContentView3()
} else {
ContentView1()
}
}
}
您在 中的逻辑错误if
,因此“15:30”进入ContentView2
。正确的逻辑可能如下所示:
if (hours == 12 && minutes >= 30) || (hours > 12 && hours < 15) {
ContentView2()
} else if (hours >= 15 && hours < 18) || (hours == 18 && minutes < 30) {
ContentView3()
} else {
ContentView1()
}
但我更喜欢使用另一种方法:将您的值对转换为单个值 - 在本例中为天分钟,并在 : 中使用此值switch
:在这种情况下,您可以使用对我来说更具可读性的范围:
var body: some View {
switch hoursAndMinutesToMinutes(hours: dateComps.hour!, minutes: dateComps.minute!) {
case hoursAndMinutesToMinutes(hours: 12, minutes: 30)...hoursAndMinutesToMinutes(hours: 14, minutes: 59):
ContentView2()
case hoursAndMinutesToMinutes(hours: 15, minutes: 00)...hoursAndMinutesToMinutes(hours: 18, minutes: 30):
ContentView3()
default:
ContentView1()
}
}
func hoursAndMinutesToMinutes(hours: Int, minutes: Int) -> Int {
hours * 60 + minutes
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句