Ho eseguito una funzione che funziona nei seguenti casi: - 1) con o senza # 2) valori di 3 e 6 caratteri # 000 nonché # 000000 3) In caso di cifre aggiuntive più di sei ignora le cifre aggiuntive
//Function Call
UIColor *organizationColor = [self colorWithHexString:@"#AAAAAAAAAAAAA" alpha:1];
//Function
- (UIColor *)colorWithHexString:(NSString *)str_HEX alpha:(CGFloat)alpha_range{
NSString *noHashString = [str_HEX stringByReplacingOccurrencesOfString:@"#" withString:@""]; // remove the #
int red = 0;
int green = 0;
int blue = 0;
if ([str_HEX length]<=3)
{
sscanf([noHashString UTF8String], "%01X%01X%01X", &red, &green, &blue);
return [UIColor colorWithRed:red/16.0 green:green/16.0 blue:blue/16.0 alpha:alpha_range];
}
else if ([str_HEX length]>7)
{
NSString *mySmallerString = [noHashString substringToIndex:6];
sscanf([mySmallerString UTF8String], "%02X%02X%02X", &red, &green, &blue);
return [UIColor colorWithRed:red/255.0 green:green/255.0 blue:blue/255.0 alpha:alpha_range];
}
else
{
sscanf([noHashString UTF8String], "%02X%02X%02X", &red, &green, &blue);
return [UIColor colorWithRed:red/255.0 green:green/255.0 blue:blue/255.0 alpha:alpha_range];
}}
fonte
2016-10-03 13:21:05
Secondo la documentazione, '- (BOOL) scanHexInt: (unsigned *) intValue', così si potrebbe desiderare di dichiarare' baseColor' come 'unsigned'; a parte questo, mi piace la risposta di progrmr. – Isaac