Alerts and Action Sheets
Both Alerts and Action Sheets use the similar two ways of presenting it to the user.
Modals
To present modals, SwiftUI provides the special view modifier called sheet.
Popovers
Using Popovers in SwiftUI is very similar to Alers and Action Sheets.
//
// ContentView.swift
// Test
//
// Created by Cairocoders
//
import SwiftUI
import Combine
struct ContentView: View {
@State private var showActionSheet = false
@State private var isActionSheet = false
@State private var message: Message? = nil
@State private var showModal = false
@State private var showPopover: Bool = false
var body: some View {
VStack {
//Action Sheets
HStack {
Button("Show action sheet") {
self.showActionSheet = true
}
}
.padding(.bottom)
.actionSheet(isPresented: $showActionSheet) {
ActionSheet(
title: Text("Actions"),
message: Text("Available actions"),
buttons: [
.cancel { print(self.showActionSheet) },
.default(Text("Action")),
.destructive(Text("Delete"))
]
)
}
//Action Sheets Example 2
HStack {
Button(action: {
self.isActionSheet = true
}) {
Text("ActionSheet")
.foregroundColor(Color.white)
}
.padding()
.background(Color.blue)
.actionSheet(isPresented: $isActionSheet, content: {
ActionSheet(title: Text("iOSDevCairocoders"), message: Text("SubTitle"), buttons: [
.default(Text("Save"), action: {
print("Save")
}),
.default(Text("Delete"), action: {
print("Delete")
}),
.destructive(Text("Cancel"))
])
})
}
.padding(.bottom)
//Alerts
HStack {
Button("Show alert") {
self.message = Message(text: "Hi!")
}
}
.padding(.bottom)
.alert(item: $message) { message in
Alert(
title: Text(message.text),
dismissButton: .cancel()
)
}
//Modals
HStack {
Button("Show modal") {
self.showModal = true
}
}
.padding(.bottom)
.sheet(isPresented: $showModal, onDismiss: {
print(self.showModal)
}) {
ModalView(message: "This is Modal view")
}
//Popovers
HStack {
Button("Show popover") {
self.showPopover = true
}.popover(
isPresented: self.$showPopover,
arrowEdge: .bottom
) { Text("Popover") }
}
}
}
}
struct Message: Identifiable {
let id = UUID()
let text: String
}
struct ModalView: View {
@Environment(\.presentationMode) var presentation
let message: String
var body: some View {
VStack {
Text(message)
Button("Dismiss") {
self.presentation.wrappedValue.dismiss()
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
