简体   繁体   English

定义自定义颜色Swift

[英]Define custom colors Swift

I'm rewriting my app in Swift (yes, hooray) and I'm running into the following: 我正在用Swift重写我的应用程序(是的,万岁),我遇到了以下问题:

I inherited a class, of which the definition is (.h) 我继承了一个类,其定义是(.h)

#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>

@interface MWColor : NSObject

+ (UIColor *)gray;
+ (UIColor *)green;
+ (UIColor *)themeColor;


@end

In here, I define colors, that I can use throughout my project as such: 在这里,我定义了颜色,我可以在整个项目中使用它们:

myView.backgroundColor = MWColor.gray()

Now, I want to do this in a proper Swift way. 现在,我想以适当的Swift方式做到这一点。

What would be the best approach? 什么是最好的方法? Extensions? 扩展?

Help me to be a good Swift citizen 帮助我成为一名优秀的斯威夫特公民

You can add computed colours to UIColor in an extension like this... 您可以在这样的扩展中将计算颜色添加到UIColor ...

extension UIColor {
    static var myRed: UIColor { 
        // define your color here
        return UIColor(...) 
    }
}

or even... 甚至...

extension UIColor {
    static let myRed = UIColor(... define the color values here ...)
}

Then access it like... 然后访问它...

let someColor: UIColor = .myRed

or 要么

let otherColor = UIColor.myRed

This matches the way that standard colours are defined too.. 这与标准颜色的定义方式相匹配。

UIColor.red
UIColor.yellow
UIColor.myRed

etc... 等等...

There are probably a thousand different ways to do this, but I use the following extension: 可能有一千种不同的方法,但我使用以下扩展名:

extension UIColor {

    convenience init(rgb: UInt) {
        self.init(
            red: CGFloat((rgb & 0xFF0000) >> 16) / 255.0,
            green: CGFloat((rgb & 0x00FF00) >> 8) / 255.0,
            blue: CGFloat(rgb & 0x0000FF) / 255.0,
            alpha: CGFloat(1.0)
        )
    }
}

Then you can set the color of any object using the common HEX color code of RGB colors. 然后,您可以使用RGB颜色的常见HEX颜色代码设置任何对象的颜色。 Quickly find HEX colors here: http://www.color-hex.com/ 在这里快速找到HEX颜色: http//www.color-hex.com/

view.backgroundColor = UIColor(rgb: 0xFF0000) will set the backgroundColor of view to red. view.backgroundColor = UIColor(rgb: 0xFF0000)将backgroundColor视图设置为红色。

Hope this helps 希望这可以帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM