Home > Blockchain >  Time Interval in SwiftUI
Time Interval in SwiftUI

Time:03-15

I'm working on an app and in that, I want to display different views on different times of day (e.g. View1() from 12:00 PM to : 3:00PM and View2() from 3:00 PM to 8:00 PM)

Edit: The problem here is, that when its 15:30, View1() will be opened instead of View3().

let dateComps = Calendar.current.dateComponents([.hour, .minute], from: Date())

struct MainView: View{

var body: some View{

if (dateComps.hour! >= 12 && dateComps.minute! >= 30) && dateComps.hour! <= 15 {
   View1()
} else if dateComps.hour! >= 15 && (dateComps.hour! <= 18 && dateComps.minute! <= 30) {

   View2()

} else {

   View3()
}

}

}

CodePudding user response:

If you want to change the view based on the time of day, you could try using something like DateComponents. The code for such a system is below (works with IOS 15/ Xcode 13)

//You can use anything in the brackets,such as weekday,
let dateComps = Calendar.current.dateComponents([.hour, .day, .weekday, .month], from: Date())

struct MainView: View{

    var body: some View {
        //24 Hour format, measured in ints 
        if dateComps.hour! <= 12 { 

        //If morning
        morningView()

        } else if dateComps.hour! <= 18 {

            //afternoon
            afternoonView()

        } else {

            //Other or Evening view
            eveningView()
        }
    }
}

You could also switch this stuff in a function and return a variable or something based on the time of day. Just make sure you put the thing you want from the components after the overall components name, and unwrap it - use ! or ? if you want to provide a default value.

  • Related