swiftuicolor

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


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 doesn't recognize UIColor's designated initializer in my convenience initializer:

extension UIColor {
  convenience init(rawValue red: CGFloat, green g: CGFloat, blue b: CGFloat, alpha a: CGFloat) {

    // Can not find out the designated initializer here
    self.init()

  }
}

Any solutions?


Solution

  • You can't do it like this, you have to chose different parameter names to create your own initializers/ You can also make them generic to accept any BinaryInteger or BinaryFloatingPoint types:


    extension UIColor {
        convenience init<T: BinaryInteger>(r: T, g: T, b: T, a: T = 255) {
            self.init(red: .init(r)/255, green: .init(g)/255, blue: .init(b)/255, alpha: .init(a)/255)
        }
        convenience init<T: BinaryFloatingPoint>(r: T, g: T, b: T, a: T = 1.0) {
            self.init(red: .init(r), green: .init(g), blue: .init(b), alpha: .init(a))
        }
    }
    

    let green1 = UIColor(r: 0, g: 255, b: 0, a: 255)  // r 0,0 g 1,0 b 0,0 a 1,0
    let green2 = UIColor(r: 0, g: 1.0, b: 0, a: 1.0)  // r 0,0 g 1,0 b 0,0 a 1,0
    
    let red1 = UIColor(r: 255, g: 0, b: 0)  // r 1,0 g 0,0 b 0,0 a 1,0
    let red2 = UIColor(r: 1.0, g: 0, b: 0)  // r 1,0 g 0,0 b 0,0 a 1,0