Building a Custom UIPageControl in Swift
To help myself and our community establish good design patterns, I am trying to share my thought process every time I build something in Swift for the first time. In my current project, we need to build something similar to a UIPageControl, but with icons. It will control a UIScrollView and advance to a certain ‘page’ in the scroll view. My design goal is to use Enums to represent the different icons AND to hide the ObjC #selector() implementation details.
Here is my first take on this:
PageControl is a Class that basically wraps a UIStackView full of UIButtons. It inherits from NSObject because it acts as a target for the UIButtons.
The ViewCategory Enum represents the different type of pages and provides a convenient way to create a button with the appropriate image.
This is a pretty simple implementation and doesn’t address the possibility of custom layouts, different types of buttons, and probably 12 other things I’m not even thinking of. The UIStackView is publicly accessible, so spacing/distribution/alignment/axis could all be changed. Maybe it would make sense to pass in a config Struct in addition to the array of UIViews to configure the stack.
Let’s see it in action:
We now can easily just pass in Enum cases to configure our PageControl. It informs its delegate when a button is pressed and which index that button is.
Alright, what did I do wrong? What can I do better? Is there a better pattern for creating custom UI? Jesse Squires recently said that “using enums as configuration … is an anti-pattern” and I tend to agree, especially when building generic UI components. We could easily change this enum to accept a string property or use a ‘Configuration Model’ like Jesse uses.
Hit me up @iAmChrisTruman with opinions, criticism, trolling, and/or money.