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

后端 未结 3 1866
花落未央
花落未央 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:10

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

    extension UIColor {
        convenience init(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(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
    

提交回复
热议问题