How to add initializers in extensions to existing UIKit classes such as UIColor?

后端 未结 3 1867
花落未央
花落未央 2021-02-06 23:39

The Swift documentation says that adding initializers in an extension is possible, and the example in the document is about adding an initializer to a struct. Xcode doe

3条回答
  •  误落风尘
    2021-02-07 00:01

    Changing the parameter types will also work.

    extension UIColor {
    
        convenience init(red: Int, green: Int, blue: Int, alpha: CGFloat) {
    
            let normalizedRed = CGFloat(red) / 255
            let normalizedGreen = CGFloat(green) / 255
            let normalizedBlue = CGFloat(blue) / 255
    
            self.init(red: normalizedRed, green: normalizedGreen, blue: normalizedBlue, alpha: alpha)
        }
    }
    

    Usage:

    let newColor: UIColor = UIColor.init(red: 74, green: 74, blue: 74, alpha: 1)
    

    I would usually forget the redundant work of dividing the component values by 255. So I made this method to facilitate me.

提交回复
热议问题