Skip to content

Instantly share code, notes, and snippets.

@klein-artur
Created July 9, 2022 12:40
Show Gist options
  • Save klein-artur/de4d9034ee862be6290de33cacbbacff to your computer and use it in GitHub Desktop.
Save klein-artur/de4d9034ee862be6290de33cacbbacff to your computer and use it in GitHub Desktop.
A viewmodifier for SwiftUI to make handling multiple alerts in one view file much easier.

How To:

Just add a state to your view like this:

@State var alertData: AlertData? = nil

and add the modifier to your top view like this:

  .customAlert(data: $alertData)

Whenever you want to show an alert, you can do it like this:

self.alertData = AlertData(
    title: "Some Title",
    message: "Some important but optional message",
    actions: [
        AlertButton(title: "Say Yes!") {
            // do what to do here.
        },
        AlertButton(title: "Say No!", style: .cancel) {
            // do what to do here.
        }
    ]
)
import Foundation
import SwiftUI
struct AlertButton: Identifiable {
var id: String {
title
}
let title: String
let style: ButtonRole?
let action: (() -> Void)?
}
struct AlertData {
let title: String
let message: String?
let actions: [AlertButton]
}
struct CustomAlertModifier: ViewModifier {
@Binding var data: AlertData?
func body(content: Content) -> some View {
content
.alert(
data?.title ?? "",
isPresented: Binding<Bool>(
get: {
data != nil
},
set: { value in
data = value ? data : nil
}
), presenting: data
) { data in
ForEach(data.actions) { action in
Button(role: action.style, action: action.action ?? { }) {
Text(action.title)
}
}
} message: { data in
if let message = data.message {
Text(message)
}
}
}
}
extension View {
func customAlert(data: Binding<AlertData?>) -> some View {
self.modifier(CustomAlertModifier(data: data))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment