我有一个关于在 swift 中创建自定义 UIColor 的问题。
我使用了以下扩展代码:
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)
我想将其加载到shadowColor中,使用以下代码:
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
}
}
但是我使用的每个组合都不起作用。每次它都说我应该使用as! CGColor,但是当我这样做时,应用程序崩溃了。
请帮助我
谢谢
最佳答案
在您的代码中,您当前正在向 self.layer.shadowColor = (Loading code here)
提供 UIColor
,这应该会导致编译器错误。
您创建的扩展没问题。在实例化新的 UIColor
实例后,只需使用 UIColor
的 .cgColor
属性即可。这将是示例代码:
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
}
}
关于swift - 为 UIColor 创建自定义颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46308103/