me.needHelp
me.needHelp

Reputation: 55

Custom NSColor?

I have the following code inside a button, which successfully changes the view's background colour:

func bgcol() {
    self.view.layer?.backgroundColor = NSColor.blue.cgColor
}

I would like to change the colour to a custom rgb colour, but everything I have found seems to use UI colour, which I presume is for iOS only?

I have also looked at the documentation for NSColor, but as a complete beginner, I unfortunately cannot understand it :(

Could someone please tell me how I modify my code, to use a custom rgb colour.

Thank you all in advance.

UPDATE: I now have this code - but nothing has changed :(:

func bgcol() {
    let customColor = NSColor(red: 99.0, green: 0.0, blue: 0.0, alpha: 1.0)
    self.view.layer?.backgroundColor = customColor.cgColor
}

UPDATE 2: Ok, in the viewController.swift file I have the following code near the top:

func bgcol() {
let customColor = NSColor(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
self.view.layer?.backgroundColor = customColor.cgColor}

Then, in the VIEW DID LOAD() I call

bgcol()

Lets say for example I want the colour to be r220 g123 b45, I have no idea how to set that as the background colour?

Being completely new, the syntax is freaking me out :(

Upvotes: 1

Views: 1989

Answers (1)

shallowThought
shallowThought

Reputation: 19602

Command+click NSColor to see what it offers:

/* Create NSCustomColorSpace colors that are compatible with sRGB colorspace; these variants are provided for easier reuse of code that uses UIColor on iOS. It's typically better to specify the colorspace explicitly with one of the above methods.

If red, green, blue, or saturation, brightness, or white values are outside of the 0..1 range, these will create colors in the extended sRGB (or for colorWithWhite:alpha:, extendedGenericGamma22GrayColorSpace) color spaces. This behavior is compatible with iOS UIColor.
*/
@available(OSX 10.9, *)
public /*not inherited*/ init(white: CGFloat, alpha: CGFloat)

@available(OSX 10.9, *)
public /*not inherited*/ init(red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat)

@available(OSX 10.9, *)
public /*not inherited*/ init(hue: CGFloat, saturation: CGFloat, brightness: CGFloat, alpha: CGFloat)

You could use this initializer:

let customColor = NSColor(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)

Upvotes: 2

Related Questions