Quick Expansion Doesn't Work

I added an extension for UIColor for some colors that I use throughout the application. Here is an example:

extension UIColor { func appLightGrayColor() -> UIColor { return UIColor(red: 190.0/255.0, green: 190.0/255.0, blue: 190.0/255.0, alpha: 1.0) } func grayScaleColor(grayScale : CGFloat) -> UIColor { return UIColor(red: grayScale/255.0, green: grayScale/255.0, blue: grayScale/255.0, alpha: 1.0) } } 

However, when I try to call it, the only way I was able to compile without errors is the following:

 UINavigationBar.appearance().barTintColor = UIColor.appLightGrayColor(UIColor())() 

Here is what I get with autocomplete:

enter image description here

What am I doing wrong?

+6
source share
2 answers

While Brian's answer is still correct, with the release of Swift 3, the preferred way for Swifty to do things has changed a bit.

With Swift 3, the predefined UIColors are used accordingly:

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

Therefore, if you want something like this, like the following ...

 var myColor: UIColor = .myCustomColor 

... then you would define the extension as follows:

 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 
+2
source

You added an instance method, but what you really want is a class method

 extension UIColor { class func appLightGrayColor() -> UIColor { return UIColor(red: 190.0/255.0, green: 190.0/255.0, blue: 190.0/255.0, alpha: 1.0) } class func grayScaleColor(grayScale : CGFloat) -> UIColor { return UIColor(red: grayScale/255.0, green: grayScale/255.0, blue: grayScale/255.0, alpha: 1.0) } } 
+18
source

Source: https://habr.com/ru/post/971260/


All Articles