How to create toast in SwiftUI
A simple and beautiful alert.
Sometimes you just want to show the user that some process is loading, or completed without the need to “Dismiss” the alert. Using the built-in alert when a user favorited a song or add it to a library is not a good UX.
We all familiar with Apple’s Music alerts popups when we like/add a song to our library. This is a great way presenting simple and beautiful information to the user.
So I thought why not making an open-source library and recreating Apple’s alerts appearance and behavior as much as possible for SwiftUI.
How it’s going to look like:
Let’s begin!
First, install this repo:
After the installation, Just add the .toast
view modifier on any view builer that you would like to present an alert, assign a Binding<Bool>
and if you want, you can also add duration.
The .toast
view modifier function expects to receive an AlertToast
just like the built-in alert system in SwiftUI.
The final code with a simple text alert should look like this:
Importent!
When returning
AlertToast
, you must havetype:
, any other parameter can be removed or assignednil
.
Alert Types and Parameters
The default alert duration is 2 seconds, you can add duration:
to the .toast
view modifier to change the time duration for the presented alert, OR you can set duration to 0 to disable auto dismiss.
Currently, there’s 6 alert types I created for you to use:
- Regular: Alert with only text.
- Complete/Done: Alert with built-in checkmark animation.
- Error: Alert with built-in xmark animation.
- System Image: Alert with SFSymbols images.
- Image: Alert with a named image from Assets.
- Loading: Activity Indicator (Spinner).
Every type has its associated values to assign like Color & Image names. I will pass here the whole Alert Types with associated types that they require.
Oh, one more thing, you can add to a single view as many alerts as you like!
Bonus
What if you want to present alert after successful login, other network action or some kind of process? and you don’t want to create a bunch of Bool
for each kind of alert. One alert, and one toggle.
You can create an ObservableObject
and implement an EnvironmentObject
to use it from anywhere in the project without calling again and again .toast
.
The important thing here is to apply the view modifier to your first View in the hierarchy, and init a new AlertToast from other views on the same ObservableObject.
This method will automatically present the alert upon init:
That’s all!
Thank you very much for reading this article! This is the very first article that I’m writing so I’ll appreciate any comment from you guys so I could do better :)