SwiftUI - Alert
Alert 是 SwiftUI 中向用户显示的一种特殊类型的弹出消息或通知。它通常在执行关键操作之前向用户显示一些重要消息。警报旨在在用户执行任何关键任务时引起用户的注意或确认。
警报框由重要消息和一个或两个按钮组成,例如 OK、Delete、Cancel 等。警报框通常用于显示信息、确认、警告或错误消息。在本章中,我们将学习如何在 SwiftUI 中创建警报框。
在 SwiftUI 中创建警报
在 SwiftUI 中,我们可以使用预定义的 alert() 修饰符创建警报框。此修饰符使用给定的数据显示警报对话框。此修饰符仅受 iOS、tvOS 和 watchOS 支持。
要显示警告框,请将 isPresented 设置为 true,并且数据中必须包含内容。显示警告框后,数据参数的值不会改变。
语法
以下是语法 −
alert<A, T>( _ title: Text, isPresented: Binding<Bool>, presenting data: T?, @ViewBuilder actions: (T) -> A ) -> some View where A : View
参数
以下是修饰符 − 接受的参数
title:表示警报的标题。
isPresented:布尔值检查警报是否存在。每当用户对警报消息采取行动时,系统都会将其值设置为 false。
data:它是给定警报的可选真实来源。在这里系统将内容传递给修饰符闭包。我们可以在警报框中显示此数据。
action:它是一个返回警报操作的 viewBuilder。
示例 1
以下 SwiftUI 程序创建一个警报框。
import SwiftUI
struct ContentView: View {
@State private var myAlert : Bool = false
var body: some View {
VStack{
Button("Click Here"){
myAlert = true
}
.clipShape(Rectangle())
.background(.gray)
.foregroundStyle(.white)
.font(.largeTitle)
.alert("Alert", isPresented: $myAlert){
Button("Ok", role: .cancel){}
}message: {
Text("If you click on this button your system will hanged")
}
}
}
}
#Preview {
ContentView()
}
输出
示例 2
以下 SwiftUI 程序创建一个带有多个按钮的警告框。
import SwiftUI
struct ContentView: View {
@State private var myAlert : Bool = false
@State private var username = ""
@State private var password = ""
var body: some View {
VStack{
TextField("Username", text: $username).textFieldStyle(.roundedBorder)
TextField("passcode", text: $password).textFieldStyle(.roundedBorder)
Button("Click Here"){
myAlert = true
}.font(.largeTitle)
.alert("Alert", isPresented: $myAlert){
Button("Signup", role: .none){}
Button("Cancel", role: .cancel){}
}message: {
Text("Do you want to SignUp or not?")
}
}
}
}
#Preview {
ContentView()
}
输出

