How to access extension of UIColor in Swift?

后端 未结 9 1510
猫巷女王i
猫巷女王i 2020-12-10 01:15

I am very new to swift and trying to create an extension of UIColor class as

extension UIColor{

    func getCustomBlueColor() -> UIColor {
        retur         


        
9条回答
  •  情书的邮戳
    2020-12-10 02:18

    You defined a instance function. It means you need an instance of UIColor in case to use getCustomBlueColor()-method.

    It looks like you want to have a class method, instead of the instance method. So you have to change your definition like this:

    extension UIColor{
        class func getCustomBlueColor() -> UIColor{
            return UIColor(red:0.043, green:0.576 ,blue:0.588 , alpha:1.00)
        }
    }
    

    Note the 'class' before func, so the method is now accessible as a class method.

    The same story using class methods in a structure:

    struct MyColors{
        static func getCustomBlueColor() -> UIColor{
            return UIColor(red:0.043, green:0.576 ,blue:0.588 , alpha:1.00)
        }
    }
    let color = MyColors.getCustomBlueColor()
    

    If you just want to have a class with some color definitions, I recommend you to use a struct over a class or extension:

    struct MyColors{
        static var getCustomBlueColor = { return UIColor(red:0.043, green:0.576 ,blue:0.588 , alpha:1.00) }
    }
    let color = MyColors.getCustomBlueColor()
    

提交回复
热议问题