我使用UILabel显示文本,有时显示正确的颜色,有时则不显示。我使用的是一个简单的UILabel对象,下面是我的代码:
UILabel *costomerTel = [[UILabel alloc] init];
costomerTel.textColor = RSColor(@"#0b192e");
costomerTel.font = RSFont(12);
costomerTel.text = @"+86 18888888888"
[self addSubview:costomerTel];
UILabel *costomerDesc = [[UILabel alloc] init];
costomerDesc.textColor = RSColor(@"#0b192e");
costomerDesc.font = RSFont(12);
costomerDesc.text = @"北京·项目经理"
[self addSubview: costomerDesc];
下面是图片,它在iPhone中显示: the top label's color is not correct
RSColor代码:
+ (UIColor *) colorWithHexString : (NSString *) color
{
NSString *cString = [[color 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];
// Separate into r, g, b substrings
NSRange range;
range.location = 0;
range.length = 2;
//r
NSString *rString = [cString substringWithRange:range];
//g
range.location = 2;
NSString *gString = [cString substringWithRange:range];
//b
range.location = 4;
NSString *bString = [cString substringWithRange:range];
// Scan values
unsigned int r, g, b;
[[NSScanner scannerWithString:rString] scanHexInt:&r];
[[NSScanner scannerWithString:gString] scanHexInt:&g];
[[NSScanner scannerWithString:bString] scanHexInt:&b];
return [UIColor colorWithRed:((float) r / 255.0f) green:((float) g / 255.0f) blue:((float) b / 255.0f) alpha:1.0f];
}
任何帮助都表示赞赏。谢谢
答案 0 :(得分:0)
只需将此代码替换为以下代码
即可// Separate into r, g, b substrings
NSRange range;
range.location = 0;
range.length = 2;
替换为此代码
// If Hex String Has Alpha Component
NSInteger startRange = 0;
CGFloat colorAlpha = 1.0f;
// Separate into a, r, g, b substrings
NSRange range;
range.length = 2;
if ([cString length] == 8) {
range.location = startRange;
NSString *aString = [cString substringWithRange:range];
colorAlpha = [self alphaFromHexCode:aString];
startRange = 2;
}
如果您仍然面临问题,请告诉我。
+ (CGFloat)alphaFromHexCode:(NSString *)hexCode {
unsigned int per;
[[NSScanner scannerWithString:hexCode] scanHexInt:&per];
return ((float) per / 255.0f);
}
在这里,它也将转换你的8位十六进制颜色,这可能是我们在Android和有时网络使用。
所以它就像@“00FFFFFF”意味着前两个char包含颜色的alpha,所以你必须找出该颜色的alpha。