Named Colors crash in Interface Builder builds
Asked Answered
K

1

8

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

Ken answered 14/6, 2018 at 7:31 Comment(4)
not really sure whats causing the crash in your case though, I tried creating color set and used the color set in storyboard and it loaded fine. Even when u assign images to various UI components in storyboard images will be loaded from asset library itself. Had asset library not loading been the case it should have crashed there as well isnt it?Dandridge
Please share the crash logObject
I'm not asking about the crash. It happens when UIColor(named: "primaryColor") is forcibly unwrapped, which returns nil in the Interface Builder only. My question is how to get it to return non-nil colors in the Interface Builder environment.Ken
I'm facing the exact same problem. Everything works fine, but all my custom IBDesignable xibs that references named color from xcassets programatically doesn't build on IBInspector. Looks like a bug within xcode.Morality
L
6

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)

Loudermilk answered 20/2, 2020 at 14:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.