Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
354 views
in Technique[技术] by (71.8m points)

ios - How to access extension of UIColor in Swift?

I am very new to swift and trying to create an 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...