Swift IX

Introduction

Every time I attempt to implement a new UI control the designer throws at me, I try my best to make it as reuable as possible so it can be open-sourced later on. Sometimes it works, more than not it just ends up a waste of time ^^;

So, this time, I am trying again to make it reusable, and I’m using IBInspectable, IBDesignable and Swift dynamic frameworks. On top of that, I wanted the design to be customizable through the appearance proxy, so I can plug in the style colors that PaintCode generates. All that was a nice attempt, and it worked! Also, I ended up with a nice wealth of knowledge, that will be summed up in today’s post.

UIAppearance

The appearance proxy is part of UIKit that allows you to easily customize the appearance of UIKit controls in your application. For example, you can easily set the tintColor of all your UINavigationBar instances using:

UINavigationBar.appearance().tintColor = UIColor.whiteColor()

Just make sure you do it as early as possible, since calling the method after a UINavigationBar is created won’t affect it.

Obviously, you can then override this color on as-needed basis afterwards.

Now, I really wanted that for my control, especially since I use StyleKit, from PaintCode. I remember searching in the past, without much luck. I decided to search again, and Vioala. A guy posted an answer on stack overflow 10 hours ago! Awesome!

So, here is how I ended up supporting appearance proxy:

public dynamic var trackColor: UIColor {
    set { trackShape.strokeColor = newValue.CGColor }
    get { return UIColor(CGColor: trackShape.strokeColor) }
}

Yup! that’s all, folks!. With that, you can customize the control as follows:

CircularProgress.appearance().trackColor = StyleKit.progressTrackColor
CircularProgress.appearance().fillColor = StyleKit.progressFillColor

Ultimately, this guy deserves all the credit for this.

IBAwesome

If you are still planning to support iOS 7, stop here. Come back when you can ditch it, since this all depends dynamic frameworks in order to work, and that itself is only supported on iOS 8+.

Now, I won’t go into the details of how to support the IBAwesome, since it is extensively covered here, here, and even here. What I will go into, however, is a bit about how I personally ended up using them.

Here is how my control looks like:

image

Now, you can see that I made the track color, fill color, track thickness, track progress all inspectables. The reason is that I want to specify those values individually for each component.

Other properties, like the color of the text and the text font are shared among all the controls, so I would rely on the appearance proxy to set those up, and I will see them on the running app.

Conclusion

Try your best to embrace this new way of breaking your app into smaller frameworks, it really pays off. Also, the rule of thumb here is, make shared control properties accessible via UIAppearance and the rest as IBInspectable.