How to access extension of UIColor in Swift? How to access extension of UIColor in Swift? ios ios

How to access extension of UIColor in Swift?


You have defined an instance method, which means that you can callit 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 becauseInstance 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 toexplain 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.


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


Swift 3, Swift 4, Swift 5:

extension UIColor {   static let myBlue = UIColor(red:0.043, green:0.576 ,blue:0.588, alpha:1.00) }

Use:

btnShare.setTitleColor(.myBlue, for: .normal)

Or

self.view.backgroundColor = .myBlue

If you use Color Set in *.xcassets (iOS11+).For example, you have a color with the name «appBlue». Then:

extension UIColor {private static func getColorForName(_ colorName: String) -> UIColor {    UIColor(named: colorName) ?? UIColor.red}static var appBlue: UIColor {    self.getColorForName("appBlue")}}

Use:

self.view.backgroundColor = .appBlue


matomo