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()
}
}
}
CodePudding user response:
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
}
CodePudding user response:
Just remove the else
: so both ContentView2()
and ContentView3()
will appear independently.
Now, if you want ContentView1()
to appear only when none of the others is there, it'd be better to create a couple more computed variables that can be combined for this purpose.
See example below:
let dateComps = Calendar.current.dateComponents([.hour, .minute], from: Date())
struct MainView: View {
var body: some View {
// Moved condition to a variable, see below
if show1 {
ContentView2()
}
// Not an "else", just a separate condition
// Moved condition to a variable, see below
if show2 {
ContentView3()
}
// In case this view needs to appear when the others are not there
if !show1 && !show2 {
ContentView1()
}
}
// Conditions
private var show1: Bool {
(dateComps.hour! >= 12 && dateComps.minute! >= 30) && dateComps.hour! <= 15
}
private var show2: Bool {
dateComps.hour! >= 15 && (dateComps.hour! <= 18 && dateComps.minute! <= 30)
}
}