Skip to content

Instantly share code, notes, and snippets.

@bbauman1
Created August 13, 2023 19:39
Show Gist options
  • Save bbauman1/0fd65efa0e77852f3c680eb0ee234313 to your computer and use it in GitHub Desktop.
Save bbauman1/0fd65efa0e77852f3c680eb0ee234313 to your computer and use it in GitHub Desktop.
SwiftUI Alerts
//
// AlertItem.swift
//
// Created by Brett Bauman on 7/25/23.
import Foundation
import SwiftUI
struct AlertItem: Identifiable {
let id = UUID()
let title: String
var message: String? = nil
var primaryButton: Alert.Button = .default(Text("OK"))
var secondaryButton: Alert.Button? = nil
var messageText: Text? {
if let message {
return Text(message)
} else {
return nil
}
}
}
extension View {
func alert(alertItem: Binding<AlertItem?>) -> some View {
self.alert(item: alertItem) { alertItem in
if let secondaryButton = alertItem.secondaryButton {
return Alert(
title: Text(alertItem.title),
message: alertItem.messageText,
primaryButton: alertItem.primaryButton,
secondaryButton: secondaryButton
)
} else {
return Alert(
title: Text(alertItem.title),
message: alertItem.messageText,
dismissButton: alertItem.primaryButton
)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment