簡體   English   中英

當用戶輸入的時間低於預期時間時,如何在 swiftUI 中顯示警報消息?

[英]How to show alert message in swiftUI when user enters time below the expected time?

我正在構建一個警報應用程序,我只想在用戶輸入低於 2 小時的時間時顯示一條彈出消息(警報消息),用戶應該收到一條消息,如“請輸入超過 2 小時的持續時間” ”。

這是我存儲警報值的地方

myViewModel.myModel.waketime

我想在用戶單擊下圖時顯示消息

 Image(systemName: "checkmark.circle")
                        .resizable()
                        .aspectRatio(contentMode: .fit)
                        .clipShape(Circle())
                        .sheet(isPresented: $showPlayer) {
                            SecondView()
                        }

這是用戶選擇鬧鍾時間的另一個視圖

 Text("Alarm : ")
  .font(.body)
   Spacer()
   DatePicker("", selection: self.$myViewModel.myModel.waketime, displayedComponents: .hourAndMinute)

請幫我解決這個問題!!

您可以使用Alert向用戶顯示警報。 為了在用戶單擊Image時執行此操作,您可能希望將其包裝在Button中:

struct ContentView : View {
    @State var alertShown = false
    
    var body: some View {
        Button(action: {
            if true { //here, you can check your condition for whether the alert should get triggered -- like checking `myViewModel.myModel.waketime > x`
                alertShown = true
            }
        }) {
            Image(systemName: "checkmark.circle")
                .resizable()
                .aspectRatio(contentMode: .fit)
                .clipShape(Circle())
        }.alert(isPresented: $alertShown) {
            Alert(title: Text("Please enter time more than 2 hours of duration"))
        }
    }
}

如果您不希望將Image更改為項目中的accentColor ,則可能需要將.buttonStyle(PlainButtonStyle())作為修飾符添加到Button

針對評論進行更新:您想要做的一般檢查是:

if myViewModel.myModel.waketime.timeIntervalSince1970 - Date().timeIntervalSince1970 < 60 * 60 * 2 {

但是,請注意,使用您當前僅顯示小時和分鍾的策略,這將在午夜前 2 小時開始失敗,因為DatePicker將默認為當前日期,例如,凌晨 1 點注冊為當前日期之前/時間,而不是之后。 因此,您需要添加一些額外的邏輯來解決此類問題。 例如,您可以將 24 小時添加到當前日期之前的任何時間。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM