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

问题描述

我的头文件中有这个宏:

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];

哪一种方法更好?

推荐答案

一个中间人le ground可能是您最好的选择。您可以定义常规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];
}

如果您决定坚持使用宏,则应将括号括在<$ c $附近c> 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.

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

08-30 04:41