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 swift September 2, 2024 Combine in SwiftUI and how you can rewrite the same code using async await

Combine is Apple’s declarative framework for handling asynchronous events and data streams in Swift. Introduced in SwiftUI and iOS 13, Combine leverages reactive programming principles, allowing developers to process values over time and manage complex asynchronous workflows with clarity and efficiency.

question macOS swift August 6, 2020 How to open an app's window on top of all others in Swift?

You can open your app’s window on top of all other open application windows with the below code:

question swiftui swift October 7, 2024 How to zoom in and zoom out a SwiftUI view?

In a macOS or iOS app, you can easily add a zoom feature to any SwiftUI view with the scaleEffect modifier. In the below example, I am using a Slider to control the zoom level. Here’s how you can implement zooming in and out with a slider: