swift - 为 UIColor 创建自定义颜色

标签 swift uicolor

我有一个关于在 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/

相关文章:

ios - 如何在 Xcode 中使用 for 循环声明属性

swift - 如何在代码中创建 SceneKit SCNSkinner 对象?

ios - 是否可以在 AKAudioPlayer 上使用 AKAmplitudeTracker 并测量振幅变化?

ios - UIKit 问题 - 在 IBOutlet 项目上设置颜色需要花费大量时间

ios - CAShapeLayer 描边颜色不读取十六进制颜色代码转换

ios - 调整 UITableViewCell 的高度

ios - 数组中的 UIImage 名称不断返回 nil 值。

ios - 从 UIColor 中提取 RGB 值

ios - 如何上传和查询颜色以解析 iOS/objective c

swift - swift 变量中的 UIColor 代码