如何将接口返回的十六进制颜色值设置到导航栏
Great question! Let's break this down clearly so you can get your navigation bar styled correctly.
First off, that 373737 value is a 6-digit hexadecimal color code—think of it as shorthand for RGB values. The good news is you don’t have to split it into R/G/B unless your specific framework or use case requires it. Most platforms support direct hex color usage, which is simpler and cleaner.
Option 1: Use the Hex Color Directly (Recommended)
Just add a # prefix to your value to make it #373737, then use it with your platform’s navigation bar styling tools. Here are examples for common platforms:
iOS (Swift)
UIKit doesn’t have a built-in hex-to-color initializer, but you can use a simple helper function to parse it:
func hexToUIColor(hex: String) -> UIColor { var cleanHex = hex.trimmingCharacters(in: .whitespacesAndNewlines).uppercased() if cleanHex.hasPrefix("#") { cleanHex.removeFirst() } guard cleanHex.count == 6 else { return .gray } var rgbValue: UInt64 = 0 Scanner(string: cleanHex).scanHexInt64(&rgbValue) return UIColor( red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0, green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0, blue: CGFloat(rgbValue & 0x0000FF) / 255.0, alpha: 1.0 ) } // Set the navigation bar color if let navColor = hexToUIColor(hex: "373737") { navigationController?.navigationBar.barTintColor = navColor }
Android (Kotlin)
Android’s Color class has a built-in method to handle hex strings directly:
val navBarColor = Color.parseColor("#373737") window.navigationBarColor = navBarColor
Web (CSS)
Simply drop the hex value into your stylesheet:
.navbar { background-color: #373737; }
Option 2: Split into RGB Values (If Needed)
If you must use RGB mode (e.g., for dynamic color adjustments or older platform constraints), here’s how to convert the hex string:
- The hex
373737splits into:- R:
37(hex) = 55 (decimal) - G:
37(hex) = 55 (decimal) - B:
37(hex) = 55 (decimal)
- R:
Examples of using these RGB values:
iOS (Swift)
let navColor = UIColor(red: 55/255.0, green: 55/255.0, blue: 55/255.0, alpha: 1.0) navigationController?.navigationBar.barTintColor = navColor
Android (Kotlin)
val navBarColor = Color.rgb(55, 55, 55) window.navigationBarColor = navBarColor
Web (CSS)
.navbar { background-color: rgb(55, 55, 55); }
Final Takeaway
Stick with the direct hex color approach unless you have a specific reason to use RGB—it’s less error-prone and more widely supported. Both methods will give you the same neutral gray color for your navigation bar.
内容的提问来源于stack exchange,提问作者Chandni

