I was trying to change the color of my app´s buttons by creating the color using sliders to select the values of Red, Green, Blue and Alpha. So I created an variable which held the color created by the user.
ViewController is where the buttons are. ChangeColors is the RGB Sliders 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 is the code of te RGB Slider System.
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 app crashes as soon as it open and get the following error:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -CGColor not defined for the UIColor ; need to first convert colorspace.
I really need help. Thank You.
The problem is that an instance created by the UIColor()
initialiser doesn't represent an actual color. If you look at the crash message in more detail, you'll see that it actually creates a UIPlaceholderColor
instance – which (as the name suggests) appears to act as a 'placeholder' in the absence of any color information. Therefore you can't assign it to the backgroundColor
of any of your views.
The fix is define a default color for your buttonColor
. In your case I'd advise clearColor
.
var buttonColor = UIColor.clearColor()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With