7

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

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? Jun 14, 2018 at 7:41
  • Please share the crash log
    – Vinodh
    Jun 14, 2018 at 8:27
  • 2
    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. Jun 14, 2018 at 9:49
  • 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. Jun 19, 2019 at 15:26

1 Answer 1

5

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)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.