Fade Views In/Out with Fadeable – A Swift Protocol Extension

During the production of my Pluralsight course on Managing Xcode Project Dependencies with CocoaPods, I wanted to provide viewers of the course the opportunity to see how to create and deploy a simple library out to the CocoaPods Trunk.

Inspiration

A simple idea came to mind: Create something that allows client developers of the pod to easily fade views in or out on any UIView instance. If you’ve read andrewcbancroft.com for a long time, you might remember that I wrote on this very subject already, but there, I used an extension to UIView, because protocol extensions hadn’t been invented yet!

For my course, I borrowed an idea that I first saw done by @NSFlexMonkey when he built the Rotateable protocol extension. Only instead of rotating, I’m fading, so I named it “Fadeable”!

Demo

Fadeable Gif Demo

Fadeable code sample

The “library’s” source can be found over at GitHub:

Resources

Here’s a snippet from the repository so you can see what the extension’s doing:

In the code snippet above, I define the Fadeable protocol as [Some Type] that has an alpha property, and a fadeIn() and fadeOut() function.

Then I create an extension to the Fadeable protocol and provide a simple, default implementation which will animate the alpha to 0, or to 1, depending on whether or not the client developer is fading in or out.

Finally, I extend UIView to conform to Fadeable. And that’s it! Any UIView instance can now fade in or out by simply calling the appropriate function:

Creating CocoaPod libraries

If you’re interested in seeing a full walk-through of how I created and published the Fadeable Library to the CocoaPods Trunk, I would love it if you gave Module 3 of my Pluralsight course, titled a watch! It’s titled Creating CocoaPod Libraries and covers from beginning to end, the process of creating a library that’s compatible with CocoaPods.