swift – 如何创建几个缓存的UIColor

我的代码中有自定义颜色.我多次使用它们,我想只分配一次.

情况/问题

如果我们看一下UIColor标题,我们可以看到以下内容

[...]

// Some convenience methods to create colors.  These colors will be as calibrated as possible.
// These colors are cached.

open class var black: UIColor { get } // 0.0 white

open class var darkGray: UIColor { get } // 0.333 white

[...]

我已经创建了UIColor的扩展,如下所示:

import UIKit

extension UIColor {

    class func colorWithHexString(_ hex: String) -> UIColor {

        print("\(#function): \(hex)")

        // some code,then it return a UIColor

        return UIColor(
            red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,blue: CGFloat(rgbValue & 0x0000FF) / 255.0,alpha: CGFloat(1.0)
        )

    }

    // Option A
    open class var myColorOne : UIColor {
        get {
            return colorWithHexString("AABBCC")
        }
    }

    // Option B
    class func myColorTwo() -> UIColor {
        return colorWithHexString("DDEEFF")
    }
}

从那里我可以轻松地使用我的颜色,具有变量或功能.

// A
UIColor.myColorOne

// B
UIColor.myColorTwo()

可悲的是,我对此并不满意.实际上,每次我想使用这些颜色时:都会进行新的UIColor分配.

我试过的

Apple设法让他们的颜色显然被缓存了.我也想自己这样做.我尝试了几件事,但似乎没有一件事情是理想的.

1 – 使用dispatch_once✗

在Swift页面上可见:Swift中不再提供自由函数dispatch_once.

2 – 创建常量(let)✗

我收到以下错误:扩展可能不包含存储的属性

3 – 创建单身〜

它确实有效(每种颜色只创建一次),具体如下

import UIKit

class Colors : UIColor {

    // Singleton
    static let sharedInstance = Colors()

    let myColorOne : UIColor = {
        return UIColor.colorWithHexString("AABBCC")
    }()

    let myColorTwo : UIColor = {
        return UIColor.colorWithHexString("DDEEFF")
    }()

}

但它迫使我再增加一个文件调用我的颜色

Colors.sharedInstance.myColorOne

难道没有办法像UIColor.myColorOne那样获得我想要的颜色并让它们像Apple一样缓存吗?

您可以使用与中的相同方法
Using a dispatch_once singleton model in Swift,即静止
常量存储属性
这是懒惰地初始化(只有一次).这些可以定义
直接在UIColor扩展中:
extension UIColor {
    convenience init(hex: String) {
        // ...          
    }

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

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...