Macro 比 UIColor 更适合设置 RGB 颜色吗? [英] Is Macro Better Than UIColor for Setting RGB Color?

查看:37
本文介绍了Macro 比 UIColor 更适合设置 RGB 颜色吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的头文件中有这个宏:

I have this macro in my header file:

#define UIColorFromRGB(rgbValue) 
        [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 
                        green:((float)((rgbValue & 0xFF00) >> 8))/255.0 
                         blue:((float)(rgbValue & 0xFF))/255.0 
                        alpha:1.0]

我在我的 .m 文件中使用它作为这样的东西:

And I am using this as something like this in my .m file:

cell.textColor = UIColorFromRGB(0x663333);

所以想问问大家这样比较好还是应该用这种方式:

So I want to ask everyone is this better or should I use this approach:

cell.textColor = [UIColor colorWithRed:66/255.0
                                 green:33/255.0
                                  blue:33/255.0
                                 alpha:1.0];

哪种方法更好?

推荐答案

中间立场可能是您的最佳选择.您可以定义常规 C 或 Objective-C 函数来执行您的宏现在正在执行的操作:

A middle ground might be your best option. You could define either a regular C or objective-C function to do what your macro is doing now:

// As a C function:
UIColor* UIColorFromRGB(NSInteger rgbValue) {
    return [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0
                           green:((float)((rgbValue & 0xFF00) >> 8))/255.0
                            blue:((float)(rgbValue & 0xFF))/255.0
                           alpha:1.0];
}

// As an Objective-C function:
- (UIColor *)UIColorFromRGB:(NSInteger)rgbValue {
return [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0
                       green:((float)((rgbValue & 0xFF00) >> 8))/255.0
                        blue:((float)(rgbValue & 0xFF))/255.0
                       alpha:1.0];
}

但是,如果您决定坚持使用宏,则应该在 rgbValue 出现的任何位置加上括号.如果我决定调用你的宏:

If you decide to stick with the macro, though, you should put parentheses around rgbValue wherever it appears. If I decide to call your macro with:

UIColorFromRGB(0xFF0000 + 0x00CC00 + 0x000099);

你可能会遇到麻烦.

最后一段代码当然是最易读的,但可能是最不便携的——你不能简单地从程序中的任何地方调用它.

The last bit of code is certainly the most readable, but probably the least portable - you can't call it simply from anywhere in your program.

总而言之,我建议将您的宏重构为一个函数并保留它.

All in all, I'd suggest refactoring your macro into a function and leaving it at that.

这篇关于Macro 比 UIColor 更适合设置 RGB 颜色吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆