Create your own Toast Library from scratch in iOS

Mithilesh Parmar
Powerplay
Published in
3 min readOct 23, 2021

Giving visual feedback to the users whenever they perform certain action is integral part of any app. The feedback might be a success message, a warning, or an error, etc.

Android developers already have an edge over iOS developers in this as Android natively provides SnackBar/Toast component.

To solve this we will create our own Toast Library as shown below-

This article will be focused on the logic and development of the library.
We will not be going into details of ‘How to create and publish a cocoapod library.’ However, you can refer to this YouTube video if you wish to learn the same.

Let’s Get Started with the Coding Part

We’ll need 4 components to build this -

  • Enums to specify the position and type of the Toast
  • Builder object for the toast configuration
  • Default ToastView
  • Manager class to hold all the logic to use the Toast
  1. Let us start by defining an enum to represent the position and type of the Toast as below.

You can use ToastPosition.custom(..) to specify a custom position of the Toast as well.

2. Now, let’s define protocols and their default implementation for Toast Builder Objects.

ToastBuilder: It is used to define the icon, theme, type, time interval and position of Toast.

ToastThemeBuilder: Its used to define visuals like corner radius, background color, font and text color of Title and Message Label.

3. Create Default Toast View using the ToastBuilder

We will be creating the below outlined view using programmatic approach with AutoLayout. We will use SnapKit to constraint the view.

4. Define functionality which we want to be publicly accessible for this library in ToastEngine interface

  • Showing a Toast based on specific position and type ie., success, warning, error, info.
  • Showing a Toast with own custom builder object.
  • Showing custom view (eg. dialog) in place of the toast.

5. Last step is to create a class that implements ToastEngine’s API

We get theWindowobject from App’s AppDelegate class and then add the Toast to that Window. Before adding new Toast we loop over the subviews of Window which are of type ToastView.self and remove them.

Now, our library is ready to use.

How do we use it?

Its very simple as shown in the example below

To know how can we use custom ToastBuilder or custom View in place of the DefaultToastView. Checkout Show custom Toast with PowerplayToastKit for usage.

This has been published as an open source CocoaPod Library. You can check out the GitHub repo for full source code.

Did you know 😲 You can give up to 50 Claps for an article? Click/Tap and hold the clap button for a few seconds and BAM! Try it out 😋

Thank you for reading, hope it helps ✨ Any doubts or suggestions in the comment section are most welcome.

Follow me on Linkedin|Twitter | Github

--

--