How to make a property of a UIView subclass supports for UIAppearance in Swift

Pitiphong Phongpattranont
Pitiphong’s blog
Published in
1 min readJan 15, 2018

--

TL;DR put the dynamic keyword in front of the property declaration to make it supports for UIAppearance

UIKit has a mechanism for styling your app globally called UIAppearance. However UIAppearance is based on the dynamic behavior of Objective-C which isn’t the default behavior in Swift. So when you have your custom UIView subclass implementing in Swiftand trying to update its style globally with UIAppearance, you’ll end up with a crashing app. I had been struggling with that fact until one day I realized something

Swift has a special attribute called `dynamic` which will force that property to use the Objective-C message passing instead of the normal function table of Swift. So if you want to make a property of your custom UIView subclass, all you have to do is

Putting the `dynamic` keyword in front of the property declaration

By putting this keyword in front of the property declaration will force the Swift compiler to use the Objective-C message passing for this property which UIAppearance relies on. This will solve the crash problem and make it works properly with UIAppearance.

Here’s an example

dynamic var borderColor: UIColor? = .black {
didSet {
layer.borderWidth = 1.0
layer.borderColor = borderColor?.cgColor
}
}
BorderView.appearance().borderColor = .red

Peace.

--

--

A long time iOS Developer who also interested on the Programming, User Interface and User Experience design. Want to see my code? https://github.com/pitiphong-p