Life is like a vinyl record.

If we consider how we think about ourselves then it often seems as if there are two people in our heads. We talk to ourselves. We admonish ourselves. We praise ourselves. So who is doing this? How…

Smartphone

独家优惠奖金 100% 高达 1 BTC + 180 免费旋转




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.

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:

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:

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!

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.

This method will automatically present the alert upon init:

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 :)

Add a comment

Related posts:

Remembrance

An enchanting piece of dark poetry.. “Remembrance” is published by Oak in Poetry Palace.

Offering Incentives

Bringing on a new associate isn’t about just giving someone a job. It’s about the team. It’s about the centre itself.

The Fallacy of Feature Tests

You guys probably know about unit tests. A small, atomic test that covers the smallest unit of logic you can manage. I bet you also know about integration tests, where you test your system across…