Loading...

How to make Color conform to RawRepresentable in SwiftUI in macOS?

question swift macOS
Ram Patra Published on October 29, 2023

For various reasons you may want to convert the Color type to a String. And, below is a relatively cleaner way to do it.

import SwiftUI

extension Color: RawRepresentable {
    
    public init(rawValue: String) {
        guard let data = Data(base64Encoded: rawValue) else {
            self = .gray
            return
        }
        do {
            let color = try NSKeyedUnarchiver.unarchivedObject(ofClass: NSColor.self, from: data) ?? .gray
            self = Color(color)
        } catch {
            self = .gray
        }
    }
    
    public var rawValue: String {
        do {
            let data = try NSKeyedArchiver.archivedData(withRootObject: NSColor(self), requiringSecureCoding: false) as Data
            return data.base64EncodedString()
        } catch {
            return ""
        }
    }
}

You can use it like:

var rawColor: String = Color.blue.rawValue
var someColor: Color = Color(rawValue: rawColor)
Presentify

Take your presentation to the next level.

FaceScreen

Put your face and name on your screen.

ToDoBar

Your to-dos on your menu bar.

Ram Patra Published on October 29, 2023
Image placeholder

Keep reading

If this article was helpful, others might be too

question swiftui macos September 3, 2024 How to open and close windows programmatically in SwiftUI?

To open or close a window programmatically from outside that window using environment variables, you need to leverage the new openWindow (macOS 13+) and dismissWindow (macOS 14+) environment variables. This environment variables allow you to programmatically open and close a window by its identifier.

question macOS swift August 14, 2020 How to quit or close an app in macOS using Swift?

You can quit or exit an app with:NSApp.terminate(self)

question swiftui swift October 30, 2023 How to convert Color type to hex and vice-versa while retaining alpha information?

The below should work both on macOS and iOS with one minor change. That is, use UIColor instead of NSColor if you’re planning to use it for iOS.