// UIColor+Hex.h
@interface UIColor (Hex)
+ (nullable UIColor *)colorWithHexString:(NSString *)hexString;
+ (nullable UIColor *)colorWithHexString:(NSString *)hexString alpha:(CGFloat)alpha;
@end
// UIColor+Hex.m
@implementation UIColor (Hex)
+ (UIColor *)colorWithHexString:(NSString *)hexString {
return [self colorWithHexString:hexString alpha:1.0];
}
+ (UIColor *)colorWithHexString:(NSString *)hexString alpha:(CGFloat)alpha {
if (!hexString) return nil;
NSString *cString = [[hexString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
// 去除前綴
if ([cString hasPrefix:@"0X"]) cString = [cString substringFromIndex:2];
if ([cString hasPrefix:@"#"]) cString = [cString substringFromIndex:1];
// 長度校驗:6 (RGB) 或 8 (ARGB)
if (cString.length != 6 && cString.length != 8) return nil;
// 解析分量
NSRange range = {0, 2};
unsigned int r, g, b, a = 255;
[[NSScanner scannerWithString:[cString substringWithRange:range]] scanHexInt:&r];
range.location = 2;
[[NSScanner scannerWithString:[cString substringWithRange:range]] scanHexInt:&g];
range.location = 4;
[[NSScanner scannerWithString:[cString substringWithRange:range]] scanHexInt:&b];
if (cString.length == 8) {
range.location = 6;
[[NSScanner scannerWithString:[cString substringWithRange:range]] scanHexInt:&a];
}
return [UIColor colorWithRed:r/255.0 green:g/255.0 blue:b/255.0 alpha:a/255.0];
}
@end
[UIColor colorWithHexString:@"#FF5722"]; // Material Design 橙
[UIColor colorWithHexString:@"0x3F51B5"]; // Material Design 靛藍
[UIColor colorWithHexString:@"#4CAF50" alpha:0.5]; // 半透明綠
[UIColor colorWithHexString:@"FFEB3BFF"]; // ARGB 8位:黃色不透明
extension UIColor {
convenience init?(hexString: String, alpha: CGFloat = 1.0) {
var string = hexString.trimmingCharacters(in: .whitespacesAndNewlines).uppercased()
if string.hasPrefix("0X") { string.removeFirst(2) }
if string.hasPrefix("#") { string.removeFirst() }
guard string.count == 6 || string.count == 8 else { return nil }
var hex: UInt64 = 0
guard Scanner(string: string).scanHexInt64(&hex) else { return nil }
let r, g, b, a: CGFloat
if string.count == 6 {
r = CGFloat((hex >> 16) & 0xFF) / 255
g = CGFloat((hex >> 8) & 0xFF) / 255
b = CGFloat(hex & 0xFF) / 255
a = alpha
} else {
r = CGFloat((hex >> 24) & 0xFF) / 255
g = CGFloat((hex >> 16) & 0xFF) / 255
b = CGFloat((hex >> 8) & 0xFF) / 255
a = CGFloat(hex & 0xFF) / 255
}
self.init(red: r, green: g, blue: b, alpha: a)
}
}
// 用法
let color = UIColor(hexString: "#FF5722")
let translucent = UIColor(hexString: "4CAF5080") // 含 Alpha
Xcode 9+ Asset Catalog 支援 Color Set:
BrandPrimary),配置 Any/Dark/Light/High Contrast 顏色UIColor(named: "BrandPrimary") / [UIColor colorNamed:@"BrandPrimary"]優勢:編譯期檢查、暗黑模式自動切換、設計師可直接調整、無硬編碼字符串。