SwiftUI如何显示警报信息

290 阅读1分钟

向用户提供反馈的一种常见方式,但有时也能帮助你调试你的应用程序,那就是使用警报。

SwiftUI提供了.alert() 修改器,我们可以用它来根据某些条件显示警报。

让我们从这个例子开始,我们有一个带有计数器的Button

import SwiftUI

struct ContentView: View {
    @State var count = 0
    
    var body: some View {
        Button("Count: \(count)") {
            self.count += 1
        }
        .font(.title)
    }
}

count 达到 10 时,我想显示一个警报信息。

我们如何做到这一点呢?

我可以给ContentView 添加一个showAlert 布尔属性,并编辑Button tap action的内容。

struct ContentView: View {
    @State var count = 0
    @State var showAlert = false
    
    var body: some View {
        Button("Count: \(count)") {
            self.count += 1
            if self.count == 10 {
                showAlert = true
                self.count = 0
            }
        }
        .font(.title)
    }
}

当我们达到10时,我们将showAlert 设置为true ,并将计数设为0。

然后我在Button 视图中添加.alert() 修改器。

.alert(isPresented: $showAlert) {
    Alert(title: Text("Great!"), message: Text("You reached 10"))
}

这个警报只有在showAlert 属性为真时才会显示。当我们解除警报时,showAlert 属性会自动设置为false

这里是完整的代码。

struct ContentView: View {
    @State var count = 0
    @State var showAlert = false
    
    var body: some View {
        Button("Count: \(count)") {
            self.count += 1
            if self.count == 10 {
                showAlert = true
                self.count = 0
            }
        }
        .font(.title)
        .alert(isPresented: $showAlert) {
            Alert(title: Text("Great!"), message: Text("You reached 10"))
        }
    }
}

尝试运行该应用程序。计数器从0开始,点击按钮,计数器会增加。

直到你达到10。

然后计数器会从0开始重新计数。