Issue
I want to display different views on different times of day.
ContentView2()
from 12:30 to 15:00.
ContentView3()
from 15:00 to 18:30.
The problem here is, that when it is 15:30, ContentView2() will be opened instead of 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()
}
}
}
Solution
You have the wrong logic in if
, so "15:30" goes into ContentView2
. The correct logic may look like this:
if (hours == 12 && minutes >= 30) || (hours > 12 && hours < 15) {
ContentView2()
} else if (hours >= 15 && hours < 18) || (hours == 18 && minutes < 30) {
ContentView3()
} else {
ContentView1()
}
But I prefer using an other method: convert your values pair into a single value – in this case to day minutes, and use this value in switch
: in this case you can use ranges which looks more readable to me:
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
}
Answered By – Pylyp Dukhov
Answer Checked By – Robin (BugsFixing Admin)