0

I'm creating a simple Custom NSView that allows the user to input 3 text fields each for R,G and B values respectively. I already referenced this question and answer set here - it only accounts up to Swift 2.0. So, does anyone know the correct technique of obtaining this same effect in Swift 3.0? I can't seem to get anything that I'm doing to work. I keep getting errors of all sorts.

Here's the current technique I'm using (This seems to work... BUT it won't account for the other 2 RGB values, since it's used in the @IBAction):

//viewDidLoad
RVCustomView.wantsLayer = true

@IBAction func redValue(_ sender: AnyObject) {
    print(red.stringValue)

    var rValue = 0
    let str = red.stringValue
    if let n = NumberFormatter().number(from: str) {
        rValue = Int(CGFloat(n))
    }

    CustomNSView.layer?.backgroundColor = CGColor(red: rValue, green: 255, blue: 255, alpha: 255)

}
Community
  • 1
  • 1
KSigWyatt
  • 1,368
  • 1
  • 16
  • 33

2 Answers2

1

If you want to dynamically change the background colour of a NSView each time the value of one of the three R, G, B text views changes, you could use the controlTextDidChange(notification:) delegate method of NSTextField coupled with outlets for each of the three text fields.

The method is fired every time one of the fields is changed and you use it for reading the value of the RGB fields (via outlets) and change the colour accordingly.

 override func controlTextDidChange (notification: NSNotification?) {
    // assuming the text fields' value is between 0 and 255
    guard 
        let redValue = Float(redOutlet.stringValue),
        let greenValue = Float(greenOutlet.stringValue),
        let blueValue = Float(blueOutlet.stringValue)

        else { return }

     CustomNSView.layer?.backgroundColor = CGColor(red: CGFloat(redValue/255), green: CGFloat(greenValue/255), blue: CGFloat(blueValue/255), alpha: 255)
 }

Note : don't forget to properly set the delegate for each of the three text fields!

Bogdan Farca
  • 3,856
  • 26
  • 38
-1

I think you can just do that:

@IBAction func redValue(_ sender: AnyObject) {
     yourView.backgroundColor = UIColor(colorLiteralRed: readValue/255, green: greenValue/255, blue: blueValue/255, alpha: 1)
}
  • This will not work. Swift 3 requires the use of `.layer?.backgroundColor` before you can adjust the color. Unless there is another way of doing this. But this is the only way I've been able to make it work – KSigWyatt Oct 29 '16 at 02:54