HexString类型的颜色可能对于老程序员来说是小菜一碟,但是对于初入程序界的小菜可能就有点难攻了,下面就简单介绍大家一个方法:
1.首先新建一个方法类:UIColor+MGFoundation
2.在.h文件中声明这样一个方法
+ (UIColor *)colorWithHexString:(NSString *)stringToConvert;
3.在.m文件中实现上面的方法
+ (UIColor *)colorWithHexString:(NSString *)stringToConvert
{
NSString *cString = [[stringToConvert stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
// String should be 6 or 8 characters
if ([cString length] < 6) {
return [UIColor clearColor];
}
// strip 0X if it appears
if ([cString hasPrefix:@"0X"])
cString = [cString substringFromIndex:2];
if ([cString hasPrefix:@"#"])
cString = [cString substringFromIndex:1];
if ([cString length] != 6)
return [UIColor clearColor];
NSScanner *scanner = [NSScanner scannerWithString:cString];
unsigned hexNum;
if (![scanner scanHexInt:&hexNum]) return nil;
return [UIColor colorWithRGBHex:hexNum];
}
self.view.backgroundColor = [UIColor colorWithHexString:@"#f2f2f2"];