CGColor, not specific to UIColor, must first convert the color space. Swift 2, Xcode 7

I tried to change the color of the buttons of my application by creating a color using the sliders to select the values ​​of red, green, blue and alpha. So I created a variable containing the color created by the user.

ViewController are buttons. ChangeColors is an RGB slider system.

import UIKit import Foundation var buttonColor = UIColor() class ViewController: UIViewController { @IBOutlet var tools: UIButton! @IBOutlet var custom: UIButton! @IBOutlet var support: UIButton! @IBOutlet var donate: UIButton! override func viewDidLoad() { super.viewDidLoad() tools.backgroundColor = buttonColor custom.backgroundColor = buttonColor support.backgroundColor = buttonColor donate.backgroundColor = buttonColor } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } 

The second code is the RGB Slider system code.

 import Foundation import UIKit class ChangeColors: UIViewController { @IBOutlet var Red: UISlider! @IBOutlet var Green: UISlider! @IBOutlet var Blue: UISlider! @IBOutlet var Alpha: UISlider! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func preview(sender: AnyObject) { let rVal = CGFloat(Red.value) let gVal = CGFloat(Green.value) let bVal = CGFloat(Blue.value) let aVal = CGFloat(Alpha.value) self.view.backgroundColor = UIColor(red: rVal, green: gVal, blue: bVal, alpha: aVal) } @IBAction func change(sender: AnyObject) { let rVal = CGFloat(Red.value) let gVal = CGFloat(Green.value) let bVal = CGFloat(Blue.value) let aVal = CGFloat(Alpha.value) let color = UIColor(red: rVal, green: gVal, blue: bVal, alpha: aVal) buttonColor = color } } 

But the application crashes immediately after opening it and receives the following error:

The application terminated due to the uncaught exception "NSInvalidArgumentException", reason: "*** -CGColor is not defined for UIColor; you must first convert the color space.

I really need some help. Thanks.

+6
source share
1 answer

The problem is that the instance created by the UIColor() initializer does not represent the actual color. If you look at the crash message in more detail, you will see that it actually creates an instance of UIPlaceholderColor , which (as the name implies) acts as a “placeholder” in the absence of any color information. Therefore, you cannot assign it backgroundColor any of your views.

The fix defines the default color for your buttonColor . In your case, I would advise clearColor .

 var buttonColor = UIColor.clearColor() 
+5
source

All Articles