Search code examples
iosinterface-builderasset-catalog

Named Colors crash in Interface Builder builds


In the app I'm working on, we use named colors to manage our color scheme, which we use in code like so:

extension UIColor {
    static let primaryColor = UIColor(named: "primaryColor")!
}

This works fine in most places, but breaks when we use it as a default somewhere in a custom view that is loaded in Interface Builder, because the asset catalog containing the color can't be loaded in Interface Builder builds.

We now consider a number of workarounds to avoid the force unwrap, but really we'd like the asset catalog to simply be loaded in Interface Builder builds like everywhere else.

Is there any way to do this?

Edit:

To clarify, the colors are fine when set through the UI in Interface Builder. The crashes happen when we set it in code like this:

class CustomView: UIView {
    init() {
        self.backgroundColor = .primaryColor
    }
}

Edit 2:

I filed a radar: rdar://41244137


Solution

  • Named color works fine in Interface Builder when I use Bundle(for: AppDelegate.self) instead of default bundle (Bundle.main):

    UIColor(named: "primaryColor", in: Bundle(for: AppDelegate.self), compatibleWith: nil)