Rah*_*yas 5 iphone macros xcode objective-c uicolor
我的头文件中有这个宏:
#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]Run Code Online (Sandbox Code Playgroud)
我在我的.m文件中使用此类似的东西:
cell.textColor = UIColorFromRGB(0x663333);Run Code Online (Sandbox Code Playgroud)
所以我想问每个人都这样更好还是我应该使用这种方法:
cell.textColor = [UIColor colorWithRed:66/255.0
green:33/255.0
blue:33/255.0
alpha:1.0];Run Code Online (Sandbox Code Playgroud)
哪一个更好的方法?
woe*_*ens 17
或者创建一个单独的类别,因此您只需要导入一个.h文件:
@interface UIColor (util)
+ (UIColor *) colorWithHexString:(NSString *)hex;
+ (UIColor *) colorWithHexValue: (NSInteger) hex;
@end
Run Code Online (Sandbox Code Playgroud)
和
#import "UIColor-util.h"
@implementation UIColor (util)
// Create a color using a string with a webcolor
// ex. [UIColor colorWithHexString:@"#03047F"]
+ (UIColor *) colorWithHexString:(NSString *)hexstr {
NSScanner *scanner;
unsigned int rgbval;
scanner = [NSScanner scannerWithString: hexstr];
[scanner setCharactersToBeSkipped:[NSCharacterSet characterSetWithCharactersInString:@"#"]];
[scanner scanHexInt: &rgbval];
return [UIColor colorWithHexValue: rgbval];
}
// Create a color using a hex RGB value
// ex. [UIColor colorWithHexValue: 0x03047F]
+ (UIColor *) colorWithHexValue: (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];
}
@end
Run Code Online (Sandbox Code Playgroud)
Mar*_*ius 15
如何创建自己的:
#define RGB(r, g, b) \
[UIColor colorWithRed:(r)/255.0 green:(g)/255.0 blue:(b)/255.0 alpha:1]
#define RGBA(r, g, b, a) \
[UIColor colorWithRed:(r)/255.0 green:(g)/255.0 blue:(b)/255.0 alpha:(a)]
Run Code Online (Sandbox Code Playgroud)
然后使用它:
cell.textColor = RGB(0x66, 0x33, 0x33);
Run Code Online (Sandbox Code Playgroud)
看起来很简单,使用十六进制值,无需额外的计算开销.
Tim*_*Tim 12
中间地带可能是您的最佳选择.您可以定义常规C或Objective-C函数来执行宏现在正在执行的操作:
// 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];
}Run Code Online (Sandbox Code Playgroud)
但是,如果你决定坚持使用宏,你应该把括号放在rgbValue它出现的任何地方.如果我决定用你的宏调用:
UIColorFromRGB(0xFF0000 + 0x00CC00 + 0x000099);Run Code Online (Sandbox Code Playgroud)
你可能会遇到麻烦.
最后一点代码肯定是最易读的,但可能是最不便携的 - 你不能简单地从程序中的任何地方调用它.
总而言之,我建议将宏重构为一个函数并将其保留在该函数中.
| 归档时间: |
|
| 查看次数: |
19504 次 |
| 最近记录: |