Swift4中CGColorGetComponents不可用,如何在随机颜色数组中替换?
Hey there! Glad to help you replace the deprecated CGColorGetComponents in Swift 4, especially for your random color array use case. Let's break this down step by step.
Fixing the Deprecated
CGColorGetComponents in Swift 4 In Swift 4 and later, CGColorGetComponents was deprecated in favor of the components property on CGColor. However, we need to handle different color spaces (like RGB vs. grayscale) since random colors might come in either format, which affects the length of the components array.
Updated Working Code
fileprivate func hexyColor(color: UIColor) -> String { // Safely unwrap the components array to avoid crashes guard let components = color.cgColor.components else { return "#000000" // Fallback to black if component retrieval fails } var red: CGFloat, green: CGFloat, blue: CGFloat // Handle grayscale color spaces (only 2 components: gray + alpha) if color.cgColor.numberOfComponents == 2 { red = components[0] green = components[0] blue = components[0] } else { // Handle RGB/RGBA color spaces (4 components: red, green, blue, alpha) red = components[0] green = components[1] blue = components[2] } var hexString = "" // Loop through RGB components to build the hex string for component in [red, green, blue] { let componentInt = Int(component * 255) let hexCode = String(componentInt, radix: 16) // Pad with leading zero if the hex code is a single character hexString += hexCode.count < 2 ? "0\(hexCode)" : hexCode } return "#\(hexString.uppercased())" // Optional: Use lowercase if preferred }
Key Changes Explained
- Replace Deprecated API: Instead of
CGColorGetComponents(color.cgColor), we usecolor.cgColor.componentswith optional binding (guard let) to safely handle cases where components might be nil. - Color Space Compatibility: Random colors might use grayscale or RGB spaces. We check
numberOfComponentsto ensure we don't access invalid array indices—grayscale only has 2 components, so we reuse the gray value for all RGB channels. - Cleaner Logic: Switched from index-based looping to iterating directly over the RGB components, making the code more readable. The optional
uppercased()ensures consistent hex formatting (you can remove this if you prefer lowercase).
How to Use with Random Colors
If you're generating an array of random UIColor instances, just pass each color to this function:
let randomColors = (0..<5).map { _ in UIColor( red: CGFloat.random(in: 0...1), green: CGFloat.random(in: 0...1), blue: CGFloat.random(in: 0...1), alpha: 1.0 )} let hexColors = randomColors.map { hexyColor(color: $0) } print(hexColors) // Outputs an array of valid hex color strings
内容的提问来源于stack exchange,提问作者Fabio
相关产品推荐
相关产品推荐

