我需要使用:
[[UINavigationBar appearance] setBarTintColor:[UIColor colorWithRed:102/256.0 green:53/256.0 blue:0/256.0 alpha:1.0]];
在我的appDelegate.m中,但是我需要将UIColor设置为hex#“669900” 我怎样才能以简单的方式实现这一目标?
答案 0 :(得分:3)
将类别添加到UIColor - UIColor(HexAdditions)
在UIColor + HexAdditions.h
中#import <UIKit/UIKit.h>
@interface UIColor (HexAdditions)
+ (UIColor*)colorWithHexString:(NSString*)hexString;
+ (UIColor*)colorWithHexString:(NSString*)hexString alpha:(CGFloat)alpha;
@end
在UIColor + HexAdditions.m
中#import "UIColor+HexAdditions.h"
@implementation UIColor (HexAdditions)
+ (UIColor*)colorWithHexString:(NSString*)hexString{
hexString = [[hexString lowercaseString] stringByReplacingOccurrencesOfString:@"#" withString:@""];
switch (hexString.length) {
case 6:
hexString = [hexString stringByAppendingString:@"ff"];
break;
case 8:
//correct length
break;
default:
return nil;
break;
}
uint32_t rgba;
NSScanner *scanner = [NSScanner scannerWithString:hexString];
[scanner scanHexInt:&rgba];
return [self colorWithHexValue:rgba];
}
+ (UIColor*)colorWithHexString:(NSString*)hexString alpha:(CGFloat)alpha{
int alpha_ = alpha * 255;
hexString = [hexString stringByAppendingFormat:@"%02x",alpha_];
return [self colorWithHexString:hexString];
}
+ (UIColor*)colorWithHexValue:(uint32_t)rgba{
CGFloat red = ((rgba & 0xFF000000) >> 24) / 255.0f;
CGFloat green = ((rgba & 0x00FF0000) >> 16) / 255.0f;
CGFloat blue = ((rgba & 0x0000FF00) >> 8) / 255.0f;
CGFloat alpha = (rgba & 0x000000FF) / 255.0f;
return [self colorWithRed:red green:green blue:blue alpha:alpha];
}
您可以将其用作
[UIColor colorWithHexString:@"#669900"];