Custom AlertView using Builder Pattern in Swift
Although UIAlertController fits or satisfies necessary requirements on many or most occasions, sometimes we need to display alerts in more customizable way. By doing so, you can have configurable and colourful components in your alerts. Here it is, I will explain how you can create your own flashy custom alert view. Oh, and as a side note, I'm open to any ideas as to the best way forward. Feel free to contribute this repository.
Before you go, I would recommend you to being familiar with following terms:
- Builder Pattern
I am going to explain briefly how I made this out. I will not show you all xib and storyboard connections. You can find more details about in the repository.
Firstly, I created a view controller named CustomAlertView that includes a vertical UIStackView to add our alert view components.
It is easy to inserting and removing subviews in stack view. Also it requires less auto layout consideration.
Stack views let you leverage the power of Auto Layout, creating user interfaces that can dynamically adapt to the device’s orientation, screen size, and any changes in the available space. The stack view manages the layout of all the views in its
arrangedproperty. These views are arranged along the stack view’s axis, based on their order in the
arrangedarray. The exact layout varies depending on the stack view’s
spacing, and other properties.
Also, I have created a CustomAlertViewDelegate file that is used to control button actions.
After that, I have implemented many components that can be used in our stacked alert view. These are single label component, one to multiple button components, and image component. All views are created from XIB files. You can see them in the repo files.
Here is the code snippet of the each custom view.
Now it is time to create an alert builder class that provides a flexible solution to various element creation in our alert view.
When you run my test application you will see the following example:
Thanks for reading!