I have a question about creating a custom UIColor in swift.
I used the following extension code:
import UIKit
extension UIColor {
convenience init(red: Int, green: Int, blue: Int) {
let newRed = CGFloat(red)/255
let newGreen = CGFloat(green)/255
let newBlue = CGFloat(blue)/255
self.init(red: newRed, green: newGreen, blue: newBlue, alpha: 1.0)
}
}
let brandBlue = UIColor(red: 0, green: 127, blue: 255)
I want to load it in, shadowColor, under the following code:
class squareButton : UIButton {
override init(frame: CGRect) {
super.init(frame: frame)
self.layer.cornerRadius = 10.0
self.layer.shadowColor = (Loading code here)
self.layer.shadowRadius = 1.5
self.layer.shadowOffset = CGSize(width: 0.0, height: 2.0)
self.layer.shadowOpacity = 0.6
self.layer.masksToBounds = false
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.layer.cornerRadius = 10.0
self.layer.shadowColor = (Loading code here)
self.layer.shadowRadius = 1.5
self.layer.shadowOffset = CGSize(width: 0.0, height: 2.0)
self.layer.shadowOpacity = 0.6
self.layer.masksToBounds = false
}
}
But every combination I used won't work. Every time it says that I should use as! CGColor but when I do that, the app crashes.
Please help me
Thank you
In your code you are currently providing to self.layer.shadowColor = (Loading code here)
a UIColor
this should cause a compiler error.
The extension you created is fine. Just use the .cgColor
property of UIColor
after you instantiated your new UIColor
instance. This would then be the example code:
class SquareButton: UIButton {
let brandBlue: UIColor = UIColor(red: 0, green: 127, blue: 255)
override init(frame: CGRect) {
super.init(frame: frame)
self.layer.cornerRadius = 10.0
self.layer.shadowColor = brandBlue.cgColor
self.layer.shadowRadius = 1.5
self.layer.shadowOffset = CGSize(width: 0.0, height: 2.0)
self.layer.shadowOpacity = 0.6
self.layer.masksToBounds = false
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.layer.cornerRadius = 10.0
self.layer.shadowColor = brandBlue.cgColor
self.layer.shadowRadius = 1.5
self.layer.shadowOffset = CGSize(width: 0.0, height: 2.0)
self.layer.shadowOpacity = 0.6
self.layer.masksToBounds = false
}
}