How to create several cached UIColor

百般思念 提交于 2019-11-28 13:55:43
Martin R

You can use the same approach as in Using a dispatch_once singleton model in Swift, i.e. static constant stored properties which are initialized lazily (and only once). These can be defined directly in the UIColor extension:

extension UIColor {
    convenience init(hex: String) {
        // ...          
    }

    static let myColorOne = UIColor(hex:"AABBCC")
    static let myColorTwo = UIColor(hex:"DDEEFF")
}

There might be a better way to do it, but using a global variable (like Grimxn mentioned in the comment) is one way to solve the problem.

Below is an example you can copy & paste into a playground:

import UIKit

extension UIColor {

    class func colorWithHexString(_ hex: String) -> UIColor {
        print("allocate color")
        // do you conversion here...
        return UIColor.black
    }

}

private let myPrivateColorOne = UIColor.colorWithHexString("#ffffff")

extension UIColor {

    open class var myColorOne: UIColor {
        get {
            print("get color")
            return myPrivateColorOne
        }
    }

}

UIColor.myColorOne
UIColor.myColorOne

When you execute the code, the getter will be called twice, but colorWithHexString only once.

You could use your singleton to store the generated UIColor values as above and solve the Colors.sharedInstance.myColorOne naming problem by extending UIColor and putting the access in there:

extension UIColor {
    class func myColorTwo() -> UIColor {
        return Colors.sharedInstance.myColorTwo
    }
}

In Swift 3:

extension UIColor {
    class func color(hexString: String) -> UIColor {
        // ...
    }

    static let myColorOne = color(hexString: "AABBCC")
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!