UPDATED: added accessory image and accessory views :)

Hello everyone! This is my first Medium post, so I hope I can make an interesting contribution with this. 😉

If you have worked Swift and/or the UIKit iOS framework you probably have ever wanted to show an alert sometime and maybe used UIAlertController. The thing is that this class isn’t be very customizable, you can barely change its tint color and not much more…

So I started looking how could I make it look dark or maybe change the fonts… but I realized that the best way is just to make your own alerts.

With that said… it is still really cool to mess with Apple private API’s or internal values :D, so this is just a bunch of Swift ‘hacks’ for fun to make the UIAlertController more customizable.

The code to make the above alert was simply:

But what is DarkAlertController? Just a subclass of CustomizableAlertController.

As simple as that, CustomizableAlertController has a property for the visual effect, as well as some properties to easily change the text attributes of the title and message. (You can see the full implementation in github).

You could also change the alert background easily like this:

alert.contentView?.backgroundColor = .red

How I managed to get some of the tricks to work

How is possible to set the title and message text attributes?

Just by changing a property using KVC:

alert.setValue(newValue, forKey: “attributedTitle”)

alert.setValue(newValue, forKey: “attributedMessage”)

And the alert action attributed text? That’s a bit more tricky; you first need the label and then you use the attributedText property:

var label: UILabel? {

return (self.value(forKey: "__representer")as? NSObject)?

.value(forKey: "label") as? UILabel

}

And how did I get the visual effect view? Just doing a deep recursive search through all the subviews of the alert view.

You can find more information and the full code in the github project:

Conclusion

It is my duty to advise you against using this little hacks in production code… why? Because Apple can change it any time soon and it might not work for you or have bad results in other iOS versions.

If you want customizable alerts wait until Apple opens up a bit more that API (thing that might never happen 😂), or just build your custom alerts like these:

By subclassing UIViewController and using the storyboard:

By subclassing UIView:

There are tons of cool projects for alerts on Github too: