首页 > 解决方案 > SwiftUI 如何在警报消息中返回 nil

问题描述

在通过导入网络检查网络状态时,我正在努力删除警报中的成功消息。

        .onAppear{
        viewModel.updateData(baseCode: viewModel.baseCode)
        
        if monitor.isConnected == false {
            print("Wifi is connected")
        } else if monitor.isConnected == true {
            self.showingAlert = true
        }
    }.alert(isPresented: $showingAlert, content: {
        if monitor.isConnected == false {
            return Alert(title: Text("Connect to Internet"), message: Text("Kindly Connect to internet to get the latest rates and use the application with accurate calculations"), dismissButton: .default(Text("Okay")))
        } else {
            return Alert(title: Text("Change Rate Updated"), message: Text("You have successfully updated the change rates."), dismissButton: nil)
        }
    })

如果一切正常并且我连接到 Wi-fi 而不是

return Alert(title: Text("Change Rate Updated"), message: Text("You have successfully updated the change rates."), dismissButton: nil)

我试图不返回任何东西。因此,如果成功连接到 Internet,则不会出现该消息。

基本上,我想摆脱下面的消息。 请检查附加的图像作为参考。

标签: networkingswiftuinullalert

解决方案


Alert仅在showingAlert为真时出现。因此,您不需要使用if-statementin.alert

.alert(isPresented: $showingAlert, content: {
   return Alert(title: Text("Connect to Internet"), message: Text("Kindly Connect to internet to get the latest rates and use the application with accurate calculations"), dismissButton: .default(Text("Okay")))
})

测试这段代码

struct OrderCompleteAlert: View {
    @State private var isPresented = false
    var body: some View {
        Button("Show Alert", action: {
            isPresented = true
        })
        .alert(isPresented: $isPresented) {
            Alert(title: Text("Order Complete"),
                  message: Text("Thank you for shopping with us."),
                  dismissButton: .default(Text("OK")))
        }
    }
}

推荐阅读