Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
561 views
in Technique[技术] by (71.8m points)

objective c - Is Macro Better Than UIColor for Setting RGB Color?

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]

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

Which one is the better approach?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

or create a separate category, so you only need to import one .h file:

@interface UIColor (util)
+ (UIColor *) colorWithHexString:(NSString *)hex;
+ (UIColor *) colorWithHexValue: (NSInteger) hex;
@end

and

#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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...