User Defined Runtime Attributes — Swift

This is a quick post addressing an issue I had recently with the User Defined Runtime Attributes.

The attributes can be handy when you want to keep your code clean and avoid subclassing your view objects.

However there is an inherent problem with the runtime attributes. Xcode just doesn’t give you access to enough types.

Extensions to the rescue

Let’s try setting a shadow on the text in a UILabel for example.

Everything below shadowColor works fine. However since shadowColor is a CGColor, it won’t accept our UIColor. So instead we’ll create a CALayer extension and add it there.

import UIKit
extension CALayer {
    func shadowColorFromUIColor(color: UIColor) {
self.shadowColor = color.CGColor

Which we can then reference from within the User Defined Runtime Attributes like so:

No more messy view configuration code in your controllers and you can now access this property anywhere within your code, and interface builder.

But no one ever uses User Defined Runtime Attributes?

True. Perhaps another developer comes along and wants to change the color of the shadow. They may have a hard time figuring out where the default settings are and instead just overwrite the runtime attributes that you have set within the view controller instead.

If this is a concern, you can achieve something similar to the above by using @IBInspectable.

extension UIView {  
@IBInspectable var shadowColorFromUIColor: UIColor {
get {
if let cgShadow = layer.shadowColor {
return UIColor(CGColor: cgShadow)
} else {
return UIColor.clearColor()
set {
layer.shadowColor = newValue.CGColor

Now since extensions won’t recognise @IBDesignable — at least not yet anyway. You won’t be able see the changes live in IB, but setting these properties will work come runtime.

Besides this, the only other downfall I have heard about this method is that it doesn’t work well in frameworks.

I have my first book out called Simulations In Swift! Learn how you can use Swift playgrounds to create powerful simulations and generate digital artwork.

You can get it here: