SwiftUI Alert 组件的使用

16 min read

首先,你需要定义一个警告,它包含标题、消息和关闭按钮。如下:

Alert(title: Text("Important message"), message: Text("Wear sunscreen"), dismissButton: .default(Text("Got it!")))

要显示这个警告,有两种方法:

**方法一:**通过绑定布尔值来决定是否显示警告。例如,下面的代码创建了一个showingAlert布尔值,当点击按钮时,它会被设置为true,并触发警告的显示。

struct ContentView: View {
    @State private var showingAlert = false

    var body: some View {
        Button("Show Alert") {
            showingAlert = true
        }
        .alert(isPresented: $showingAlert) {
            Alert(title: Text("Important message"), message: Text("Wear sunscreen"), dismissButton: .default(Text("Got it!")))
        }
    }
}

**方法二:**通过绑定到符合Identifiable的某个可选状态,当对象的值发生改变时,就会显示警告。比如,下面的代码会根据选中的电视节目的不同,显示不同的警告。

struct TVShow: Identifiable {
    var id: String { name }
    let name: String
}

struct ContentView: View {
    @State private var selectedShow: TVShow?

    var body: some View {
        VStack(spacing: 20) {
            Text("What is your favorite TV show?")
                .font(.headline)

            Button("Select Ted Lasso") {
                selectedShow = TVShow(name: "Ted Lasso")
            }

            Button("Select Bridgerton") {
                selectedShow = TVShow(name: "Bridgerton")
            }
        }
        .alert(item: $selectedShow) { show in
            Alert(title: Text(show.name), message: Text("Great choice!"), dismissButton: .cancel())
        }
    }
}