Created
August 13, 2023 19:39
-
-
Save bbauman1/0fd65efa0e77852f3c680eb0ee234313 to your computer and use it in GitHub Desktop.
SwiftUI Alerts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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