时间间隔 SwiftUI

Time Intervals SwiftUI

我想在一天中的不同时间显示不同的视图。

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()
            }
        }
    }

只需删除 else: 这样 ContentView2()ContentView3() 将独立出现。

现在,如果您希望 ContentView1() 仅在其他 none 存在时出现,最好再创建几个可以为此目的组合的计算变量。

参见下面的示例:

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)
    }
    
}

您在 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
}