Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access extension of UIColor in Swift?

I am trying to create a Swift extension of UIColor class as

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

}

After this I accessed the method as

btnShare.setTitleColor(UIColor.getCustomBlueColor(**UIColor**), forState: UIControlState.Normal)

I don't know what I should pass as an argument to this statement.


2 Answers

You have defined an instance method, which means that you can call it only on an UIColor instance:

let col = UIColor().getCustomBlueColor()
// or in your case:
btnShare.setTitleColor(UIColor().getCustomBlueColor(), forState: .Normal)

The compiler error "missing argument" occurs because Instance Methods are Curried Functions in Swift, so it could equivalently be called as

let col = UIColor.getCustomBlueColor(UIColor())()

(But that would be a strange thing to do, and I have added it only to explain where the error message comes from.)


But what you really want is a type method (class func)

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

which is called as

let col = UIColor.getCustomBlueColor()
// or in your case:
btnShare.setTitleColor(UIColor.getCustomBlueColor(), forState: .Normal)

without the need to create an UIColor instance first.

like image 63
Martin R Avatar answered Sep 09 '25 19:09

Martin R


With Swift 3, predefined UIColors are used accordingly:

var myColor: UIColor = .white // or .clear or whatever

Therefore, if you want something similar, such as the following...

var myColor: UIColor = .myCustomColor

...then, you would define the extension like so:

extension UIColor {

    public class var myCustomColor: UIColor {
        return UIColor(red: 248/255, green: 248/255, blue: 248/255, alpha: 1.0)
    }

}

In fact, Apple defines white as:

public class var white: UIColor
like image 21
Gene Loparco Avatar answered Sep 09 '25 20:09

Gene Loparco