How to convert UIColor to SwiftUI‘s Color
Starting with beta 5, you can create a Color from a UIColor:
Color(UIColor.systemBlue)
Convert SwiftUI Color to UIColor
Basically, Apple doesn't intend for you to do this conversion. SwiftUI's Color
is a View
, and the design of the framework is that data flows to a View
, which is then displayed. You are never supposed to extract data back from a View
.
If you find yourself needing to use the components of a color, you should work with UIColor
, and then convert to Color
at the time you are ready to display it.
If you are trying to get the components of system colors like Color.red
, I believe they are the same as the adaptive UIColor.systemRed
, which does have accessible components.
Standard Colors documentation
Getting Dynamic UIColor from SwiftUI Color (light and dark mode)
I don't think what you want is possible. To achieve that you needed an initializer of Color
that takes a light and dark variant and a way to resolve to a cgColor
given a certain interface style (both not possible afaik). But your common ground could be the color name of your color from the asset catalogue and you could derive your SwiftUI/UIKit colors from the identifier.
struct ColorId: RawRepresentable, Equatable, Hashable {
let rawValue: String
init(_ rawValue: String) {
self.init(rawValue: rawValue)
}
init(rawValue: String) {
self.rawValue = rawValue
}
static let primaryText = ColorId("asset_name_of_primary_text_color")
}
extension ColorId {
var color: Color { Color(rawValue) }
var uiColor: UIColor? { UIColor(named: rawValue) }
}
struct SomeView: View {
let textColor = ColorId.primaryText
var body: some View {
Text("Text")
.foregroundColor(textColor.color)
}
}
final class SomeUIView: UILabel {
private let textColorId: ColorId
init(textColorId: ColorId) {
self.textColorId = textColorId
super.init(frame: .zero)
self.textColor = textColorId.uiColor
}
required init?(coder: NSCoder) { fatalError("need a color id") }
}
Then you pass around your color ids and get the UIColor
or Color
values when you need them. If you use something like RSwift you could also just pass around the ColorResource
's.
How to convert UIColor to HEX and display in NSLog
Swift 5:
func hexStringFromColor(color: UIColor) -> String {
let components = color.cgColor.components
let r: CGFloat = components?[0] ?? 0.0
let g: CGFloat = components?[1] ?? 0.0
let b: CGFloat = components?[2] ?? 0.0
let hexString = String.init(format: "#%02lX%02lX%02lX", lroundf(Float(r * 255)), lroundf(Float(g * 255)), lroundf(Float(b * 255)))
print(hexString)
return hexString
}
func colorWithHexString(hexString: String) -> UIColor {
var colorString = hexString.trimmingCharacters(in: .whitespacesAndNewlines)
colorString = colorString.replacingOccurrences(of: "#", with: "").uppercased()
print(colorString)
let alpha: CGFloat = 1.0
let red: CGFloat = self.colorComponentFrom(colorString: colorString, start: 0, length: 2)
let green: CGFloat = self.colorComponentFrom(colorString: colorString, start: 2, length: 2)
let blue: CGFloat = self.colorComponentFrom(colorString: colorString, start: 4, length: 2)
let color = UIColor(red: red, green: green, blue: blue, alpha: alpha)
return color
}
func colorComponentFrom(colorString: String, start: Int, length: Int) -> CGFloat {
let startIndex = colorString.index(colorString.startIndex, offsetBy: start)
let endIndex = colorString.index(startIndex, offsetBy: length)
let subString = colorString[startIndex..<endIndex]
let fullHexString = length == 2 ? subString : "\(subString)\(subString)"
var hexComponent: UInt32 = 0
guard Scanner(string: String(fullHexString)).scanHexInt32(&hexComponent) else {
return 0
}
let hexFloat: CGFloat = CGFloat(hexComponent)
let floatValue: CGFloat = CGFloat(hexFloat / 255.0)
print(floatValue)
return floatValue
}
How to use
let red = CGFloat(30.0)
let green = CGFloat(171.0)
let blue = CGFloat(13.0)
let alpha = CGFloat(1.0)
let color = UIColor(red: CGFloat(red/255.0), green: CGFloat(green/255.0), blue: CGFloat(blue / 255.0), alpha: alpha)
let colorCode = self.hexStringFromColor(color: color)
print(colorCode)
let resultColor = self.colorWithHexString(hexString: colorCode)
print(resultColor)
Objective-C:
- (NSString *)hexStringFromColor:(UIColor *)color {
const CGFloat *components = CGColorGetComponents(color.CGColor);
CGFloat r = components[0];
CGFloat g = components[1];
CGFloat b = components[2];
return [NSString stringWithFormat:@"#%02lX%02lX%02lX",
lroundf(r * 255),
lroundf(g * 255),
lroundf(b * 255)];
}
After getting hex code string, Call below method to get UIColor
- (UIColor *) colorWithHexString: (NSString *) hexString
{
NSString *colorString = [[hexString stringByReplacingOccurrencesOfString: @"#" withString: @""] uppercaseString];
NSLog(@"colorString :%@",colorString);
CGFloat alpha, red, blue, green;
// #RGB
alpha = 1.0f;
red = [self colorComponentFrom: colorString start: 0 length: 2];
green = [self colorComponentFrom: colorString start: 2 length: 2];
blue = [self colorComponentFrom: colorString start: 4 length: 2];
return [UIColor colorWithRed: red green: green blue: blue alpha: alpha];
}
- (CGFloat) colorComponentFrom: (NSString *) string start: (NSUInteger) start length: (NSUInteger) length {
NSString *substring = [string substringWithRange: NSMakeRange(start, length)];
NSString *fullHex = length == 2 ? substring : [NSString stringWithFormat: @"%@%@", substring, substring];
unsigned hexComponent;
[[NSScanner scannerWithString: fullHex] scanHexInt: &hexComponent];
return hexComponent / 255.0;
}
How to use
// ( R = 30, G = 171, B = 13)?
CGFloat red = 30.0;
CGFloat green = 171.0;
CGFloat blue = 13.0;
CGFloat alpha = 255.0
UIColor *color = [UIColor colorWithRed:(red/255.0) green:(green/255.0) blue:(blue/255.0) alpha:(alpha/255.0)];
NSString *colorCode = [self hexStringFromColor:color];
NSLog(@"Color Code: %@", colorCode);
UIColor *resultColor = [self colorWithHexString:colorCode];
Related Topics
Passing Data Between Tab Viewed Controllers in Swift
Swift Optional Inout Parameters and Nil
Retrieving Image from Firebase Storage Using Swift
The "Prefs" Url Scheme Is Not Working in iOS 10 (Beta 1 & 2)
Array Element Cannot Be Bridged to Objective-C
Get Description of Emoji Character
Saving Webview to Pdf Returns Blank Image
Nsdateformatter Return Wrong Date + Swift
How to Convert Hex Number to Bin in Swift
Swift - How to Mutate a Struct Object When Iterating Over It
Command Compileswiftsources Failed With a Nonzero Exit Code Xcode 10
Multiple Workers in Swift Command Line Tool
Is There a Difference Between Swift 2.0 Protocol Extensions and Java/C# Abstract Classes
Best Way to Make Amazon Aws Dynamodb Queries Using Swift
Draw Scenekit Object Between Two Points
How to Check Is a String or Number