Custom Alert Box in iOS — Swift

Gautham Sritharan
3 min readJun 8, 2021

--

Most of the apps these days come up with stunning UI designs. According to the design, alert boxes in iOS can also be customised. Here we’ll have a look into using a custom alert box instead of UIAlertController.

UIAlertController can be used to configure alerts and action sheets with the message that you want to display and the actions from which to choose. We can create a custom view to display the alerts instead of the default UIAlertController.

While developing the app, we will get into different situations where we want an alert box with one action, two actions, three actions and more. Here we’ll look into creating an action box with one action and two actions. And also customisable title and messages for the alert controller.

Okay letsss gooooooo!!!!

Alert box with one action

First, we need to design the alert box in a xib file, which you can use in required situations.

  1. In the Xcode project folder -> New file -> Cocoa touch class -> select subclass UIView and tick ‘Also create a xib file’ box and name the file as AlertViewOneAction
  2. Design your custom alert box in the AlertViewOneAction.xib file

3. In the AlertViewOneAction.swift file connect the outlets of title label, message label, button and baseview from the AlertViewOneAction.xib.

4. In the AlertViewOneAction.swift

Add a protocol to confirm ok action in AlertViewOneAction.swift

Create a struct to manage title and message

Create a connection type with ‘action’ for the OK button and confirm the delegate inside that function

Add the code code to load the nib inside the override init function

Function to show the custom alert box when it’s called.

Alert box with two action

In the same way that we can create a custom alert box with one action, we can also create a custom alert box with two actions.Create an alertbox with two actions, ‘Ok’ and ‘Cancel’ in the viewcontroller.

Here, AlertViewTwoActions.swift file has outlet action for ‘OK’ and ‘Cancel’ button. That is the major difference. The other code part is the same as AlertViewOneActions.swift

Create Viewcontroller for checking these actions

Outlet actions for for the buttons on the home screen to check the Custom alert box with one action and two actions have been created in viewcontroller.swift. In these cases, the title and message should be set during the calling process of the instances.

That’s all. We are doneeeeeee!!!!

You can find the full code in my github repository. GauthamG2

Thank you for reading. 👻🎉

--

--