Show native alerts from ViewModel with ease.
- Swift 6.0 or later
- SwiftUI
- macOS 14, iOS 17, tvOS 17, watchOS 10, macCatalyst 17 or later
-
Using GUI
Type the URL bellow to add this package to your project.
https://github.com/taka-2120/AlertPresentable.git
-
Add to
Package.swiftmanually-
Add this package to the dependencies.
dependencies: [ .package( url: "https://github.com/taka-2120/AlertPresentable.git", .upToNextMajor(from: "1.0.0") ), ],
-
Add this package product to your target.
targets: [ .target( name: "YourTarget", dependencies: [ .product(name: "AlertPresentable", package: "AlertPresentable"), ] ), ]
-
-
Setup
AlertController-
Using View Model
a. Add
AlertPresentableprotocol to your class (like view model).```swift import AlertPresentable @Observable class YourClass: AlertPresentable { ... } ```b. Add a necessary variable to your class.
```swift import AlertPresentable @Observable class YourViewModel: AlertPresentable { var alertController = AlertController() } ```c. Add
alertmodifier to your view.```swift import AlertPresentable struct YourView: View { @State private var viewModel = YourViewModel() var body: some View { yourView .alert(using: viewModel) } } ``` -
Using View Only (Above 1.1.0 or later)
import AlertPresentable struct YourView: View { @State private var alertController = AlertController() var body: some View { yourView .alert(using: $alertController) } }
-
-
Call
showAlertfunction to show the alert.// Simplest alert (Show OK button) showAlert(mode: .error, message: error.localizedDescription) // Normal alert for yes/no question. showAlert(mode: .warning, message: "Are you sure to delete this image?", action: [ .no, .yes { // Delete the image... } ]) // Complicated alert with custom title and custom actions. showAlert(title: "News", message: "New feature arrived!", action: [ .init(label: "Don't ask me again", role: .destructive) { // Set doNotAskAgain flag... }, .init(label: "Details...") { // Transition to the news page... } ])