Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Global Color Palette for Interface Builder

In swift i'm writing an extension (like Obj-C category) that maintains in code class methods of "house colors." I'm wondering if there is a way to make this color extension accessible to Interface builder using IBInspectable or something else as opposed to attaching colors specifically to UIView subclasses as i've seen in a lot of IBInspector sample usage.

extension UIColor {
    // house blue
    @IBInspectable var houseBlue: UIColor { return UIColor(red:(51/255), green:(205/255), blue:(255/255), alpha:(1)) }

    // house gray
    @IBInspectable var houseGray: UIColor { return UIColor(white:0.4, alpha: 1) }

    // house white
    @IBInspectable var houseWhite: UIColor { return UIColor.whiteColor() }
}
like image 599
achi Avatar asked Jul 21 '15 22:07

achi


People also ask

How do I add custom colors to Xcode?

To create a color from our palette, we can do it directly by selecting the Assets. xcassets folder (or creating our own . xcassets folder for colors) in the project navigator (Project Navigator). Then we right click and select New Color Set.

How do I use custom colors in Swift?

Search for the assets folder in your project, once inside you'll see everything that's added to the folder such as images, your app icon, etc. You need to create a new color by right-clicking anywhere in the list to open a menu, just click Color Set and you name the color however you want.


2 Answers

As far as I know, you can't programatically define colors that will then show up in Interface Builder, but you can extend UIColor for custom colors to use in your code:

extension UIColor {

   static func myCustomColor() -> UIColor {
     return UIColor(red: 23/255.0, green: 175/255.0, blue: 72/255.0, alpha: 1.0)
   }

}

And to reference the custom color:

myView.backgroundColor = UIColor.myCustomColor()

This doesn't completely solve your issue, but it could potentially be better to set colors programatically than through IB. It would allow you to adjust a value one time in code to change a color throughout the app rather than having to adjust it multiple times for each UI element through Interface Builder.

like image 156
Daniel Kuntz Avatar answered Nov 14 '22 17:11

Daniel Kuntz


The best solution I have found to this problem is to build an asset catalog of house colors, which can be used by Interface Builder.

https://help.apple.com/xcode/mac/current/#/dev10510b1f7

like image 25
achi Avatar answered Nov 14 '22 17:11

achi