Here’s a how-to on making custom popups in Swift for iOS. In the process, you’ll learn how to use the UIWindow class and static variables.
What We Want
Simple straight forward syntax for calling the popup, without creating a local variable. This will help reduce code clutter and make for neater syntax.
Get Started
Create a class, let’s say Popup, that will encapsulate the popup’s functionality. The window will allow the popup to cover the entire screen, including navigation bars, etc.
Why inherit from NSObject? It will be necessary later for the class to be compatible with Obj-C when we add UIGestureRecognizer protocol conformance.
Add the following code inside Popup to define its public interface and create the window.
The show function sets the window’s hidden property to true to make it visible, and the animation block animates the window from invisible to visible.
Add a button to the screen to test the popup. The button’s action should simply call the Popup’s initializer method:
Give it a run. What happens?
Absolutely nothing.
What’s wrong? The problem is that we are not keeping any reference to the popup, so it is being deallocated when the init method finishes, before the show method is called. One possible fix is to keep a reference to the Popup in the calling class:
Try this now. It works, but it complicates our code, creating an instance variable and calling show on another line. The solution is to create a static variable on the Popup class, which retains a reference to the current popup. Since there will only ever be one popup shown at a time, there will never be any problem due to multiple instances of the popup in memory.
Remove the modified syntax of the Popup initializer, and add the following code inside Popup’s initializer, after super.init():
Run the project again, and a semi-transparent popup should cover the entire screen when the button action is called.
Adding The Popup Contents
The contents for this example are a title and OK button, add these to the end of the init initializer:
You’ll get some errors which we’ll fix rightaway. Add these methods to the Popup:
Next, add this variable to the top of the Popup class:
Run the code, and you should have a working popup. Questions or comments? Please leave them below.