简体   繁体   English

SwiftUI 来自 class 中的 function 的简单弹出警报

[英]SwiftUI simple Pop-Up Alert from a function in a class

I am a little confused, I try to display a pop-up in my View when my function is true otherwise continue but I do not understand how to do it I am lost between the different ways of doing.我有点困惑,当我的 function 为真时,我尝试在我的视图中显示一个弹出窗口,否则继续但我不明白该怎么做我迷失在不同的做事方式之间。 I tried several things but something escapes me.我尝试了几件事,但有些东西逃脱了我。

Edit: The project is based on SwiftUI and the popup as to be displayed in a SwiftUI View, the function is in a class returning an ObservableObject. Edit: The project is based on SwiftUI and the popup as to be displayed in a SwiftUI View, the function is in a class returning an ObservableObject. The function is called from a SwiftUI View from a button. function 是从 SwiftUI 中调用的。

get_deliveries.swift -> into a class delivViewModel:ObservableObject get_deliveries.swift -> 进入 class delivViewModel:ObservableObject

    func cancelDeliv(delivID: String) {
        let delivRef = db.collection("av_deliveries").document(delivID)
        let isDemain = Date().dayAfter.toString()
        delivRef.getDocument { (document, error) in
            if let document = document, document.exists {
                let property = document.get("when")
                if isDemain == property as! String {
                      // Print a pop-up error
                } else {
                delivRef.updateData([
                    "taken": false,
                    "taken_by": ""
                ]) { err in
                    if let err = err {
                        print("Error updating document: \(err)")
                    } else {
                        print("Document successfully updated")
                    }
                }
            }
            }
        }
    }

Here is a basic demo of activating an alert with a Button in a View body from an ObservableObject class.这是一个基本演示,它使用来自ObservableObject class 的视图主体中的按钮激活警报。

struct ContentView: View {
// However you've initialized your class, it may be different than this.
@StateObject var progress = DeliveriesViewModel()

var body: some View {
    VStack  {
    // Other views in your View body

        // SwiftUI button to activate the Bool in ObservableObject class.
        Button {
            progress.isDisplayingAlert.toggle()
        } label: {
            Text("Toggle Alert")
        }
    }
    .alert(isPresented: $progress.isDisplayingAlert) { () -> Alert in
        Alert(title: Text("Alert Title"), message: Text("Body of Alert."), dismissButton: .cancel())
    }
  }
}

class DeliveriesViewModel: ObservableObject {

@Published var isDisplayingAlert = false

func displayAlert() {
    // other function actions...
    
    // update Published property.
    isDisplayingAlert = true
 
    // other function actions...
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM