Today I was working with a Xamarin.Mac project, and as you may know, OS X and Xcode are not very friendly guys when you need some customizations on the UI, they try to force you to use the defaults (that aqua style), but… my friend Victor made a great design and it was like a challenge for me, I told to my self, you won’t break me Apple!
So I start to google here and there, on how to change the background color of a NSView in code (since Xcode doesn’t give me the properties directly, thanks Apple 🙂 ) and results that you can user our good old friend, called Layer:
CustomView.WantsLayer = true; CustomView.Layer.BackgroundColor = NSColor.FromRgba(220,220, 220,1).CGColor;
The first thing we must do is to set property WantsLayers = true;, this will create an instance of Layer in the property CustomView.Layer, otherwise it will return null, then, from here, we are open to a big number of options here, it’s like when you unlock a hidden level in a game. Then, I set the property BackgroundColor of the Layer attribute to NSColor.FromRgba(220,220, 220,1).CGColor;
What this says is that I want the layer to be this color:
But! what happens when I run my app? I get a different color!! I get a complete white one!
But don’t panic my friend, results that the alpha value wasn’t right declared and the numbers that result from the CGColor conversion are wrong. So to keep loyal to the palette of colors used by the designer what we must do to use this method is based on the RGB from 0-255 numbers and counting the alpha value as regular percentage (I use float most of the time, don’t know if work without units or another ones). All you have to do is to divide the number that you want between 255 for the RGB colors, and by 100 the alpha value. For example:
CustomView.Layer.BackgroundColor = NSColor.FromRgba(220f/255f, 220f/255/f, 220f/255f, 100f/100f).CGColor;
And this works awesome!
Maybe you could say, “Hey! the alpha value could be straight to 1f!” yes, you can also use values between 0f-1f so feel free.
Hope this help some of you google around about this.
pd: Here is the stackoverflow Objective-C /Swift thread on Stackoverflow which enlighten me, thank you Sebastian