SwiftUI Alerts的使用示例

时间:2022-06-01 12:59:44

SwiftUI里的Alerts可以分为三类:

  • 警告对话框(Alert Dialogs)
  • 操作列表(Action Sheets)
  • 弹窗(Popovers)

警告对话框(Alert Dialogs)示例

使用SwiftUI,我们可以很容易地使用声明的方式来创建警告框以及定义操作,示例如下:

struct AlertView: View {
@State private var showingAlert = false
var body: some View {
Button(action: {
self.showingAlert = true
}) {
Text("Show Alert")
}
.alert(isPresented:$showingAlert) {
Alert(title: Text("SwiftUI 警告框"), message: Text("很容易吧"), primaryButton: .default(Text("是的")) {
print("Yeah")
}, secondaryButton: .destructive(Text("取消")))
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
AlertView()
}
}

操作列表(Action Sheets)示例

struct ActionSheetView: View {
@State private var showSheet = false
var body: some View {
Button(action: {
self.showSheet = true
}) {
Text("Show Action Sheet")
}
.actionSheet(isPresented: $showSheet) {
ActionSheet(title: Text("Are you sure?"), message: Text("This action cannot be undone"), buttons: [.destructive(Text("Delete")), .cancel()])
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ActionSheetView()
}
}

展示如下:

SwiftUI Alerts的使用示例

弹窗(Popovers)示例

弹出窗口基本上是提示。与iPhone上的modal sheet没有太大区别。设置arrowEdge属性可以设定箭头,以及箭头方向。

示例如下:

struct PopoverView: View {
@State private var showPopover: Bool = false
var body: some View {
VStack {
Button("Display Popover") {
self.showPopover = true
}.popover(
isPresented: self.$showPopover,
arrowEdge: .bottom
) { Text("Hello Popover") }
}
}
}
#if DEBUG
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
Group {
PopoverView()
.previewDevice(PreviewDevice(rawValue: "iPad Pro (11-inch)"))
.previewDisplayName("iPad Pro (11-inch)")
PopoverView()
.previewDevice(PreviewDevice(rawValue: "iPhone XS Max"))
.previewDisplayName("iPhone XS Max")
}
}
}
#endif

图片展示:

SwiftUI Alerts的使用示例