简体   繁体   English

如何替换SWIFT中Objective-C中曾经拥有的#define宏?

[英]How can I replace a #define macro I used to have in Objective-C in SWIFT?

I've been using this macro in Objective-C: 我一直在Objective-C中使用这个宏:

#define     RGBA(r, g, b, a) [UIColor colorWithRed:(r)/255.0 green:(g)/255.0 blue:(b)/255.0 alpha:(a)]

I am trying to figure out how I can get the closest thing possible in swift. 我试图找出如何在swift中获得最接近的东西。 Any ideas? 有任何想法吗?

An extension on UIColor is a valid option. UIColor的扩展是一个有效的选项。

extension UIColor {
    convenience init(_ r: Double, _ g: Double, _ b: Double, _ a: Double) {
        self.init(red: r/255, green: g/255, blue: b/255, alpha: a)
    }
}

Usage 用法

let white = UIColor(255.0, 255.0, 255.0, 1.0)

In the global scope provide: 在全球范围内提供:

func RGBA (r:CGFloat, g:CGFloat, b:CGFloat, a:CGFloat) {
  return UIColor (red: r/255.0, green: g/255.0, blue: b/255.0, alpha: a)
}

and then use it with: 然后使用它:

var theColor : UIColor = RGBA (255, 255, 0, 1)

What I did is to create a class method that returns the #define. 我所做的是创建一个返回#define的类方法。

Example: 例:

.h file .h文件

#define     RGBA(r, g, b, a) [UIColor colorWithRed:(r)/255.0 green:(g)/255.0 blue:(b)/255.0 alpha:(a)]
+ (UIColor*)RGBA:(CGFloat)r g:(CGFloat)g b:(CGFloat)b a:(CGFloat)a;

.m file .m文件

+ (UIColor*)RGBA:(CGFloat)r g:(CGFloat)g b:(CGFloat)b a:(CGFloat)a { return RGBA(r, g, b, a); }

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

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