【问题标题】:SwiftUI simple Pop-Up Alert from a function in a class来自类中的函数的 SwiftUI 简单弹出警报
【发布时间】:2021-03-28 17:37:46
【问题描述】:

我有点困惑,当我的功能为真时,我尝试在视图中显示一个弹出窗口,否则继续,但我不明白该怎么做我迷失在不同的做事方式之间。我尝试了几件事,但有些事情让我无法理解。

编辑:该项目基于 SwiftUI,并且弹出窗口将显示在 SwiftUI 视图中,该函数位于返回 ObservableObject 的类中。该函数是从按钮的 SwiftUI 视图中调用的。

get_deliveries.swift -> 进入类 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")
                    }
                }
            }
            }
        }
    }

【问题讨论】:

  • 从您的问题中不清楚此功能在哪里或它与您的视图有何关系。您还将它标记为 SwiftUI 和 UIKit,因此不清楚您要显示哪种类型的警报。
  • 您显示的代码是一个视图模型,因此它不负责直接显示警报。那是你观点的责任。您在视图模型中设置了一个状态/属性,指示存在错误,并且您的视图对此做出反应以实际显示警报或工作表或其他任何内容。

标签: ios swiftui uikit swift4


【解决方案1】:

这是一个基本演示,它使用 ObservableObject 类的视图正文中的按钮激活警报。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-28
    • 2018-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多