[SwiftUI] Use NSColorWell in SwiftUI macOS apps

November 09, 20242 min read#swift, #ios, #indie, #simrecord

While upgrading my inde app SimRecorder, I need to create a Color Picker view.

Apple has introduced the ColorPicker view since iOS 14, macOS 11. I have quickly tried it but I found out that I can’t customise the UI of the picker, as it is static and can’t be changed.

color picker

Luckily, we can use AppKit or UIKit components in SwiftUI easily, so I decided to port the NSColorWell to SwiftUI, so that I can customise the UI appearance easily.

This is the code snippet how I use NSViewRepresentable to wrap NSColorWell for SwiftUI

struct CustomColorPicker: NSViewRepresentable {
    @Binding var selectedColor: Color

    func makeNSView(context: Context) -> NSColorWell {
        let colorWell = NSColorWell()
        colorWell.target = context.coordinator
        colorWell.action = #selector(Coordinator.colorChanged(_:))
        return colorWell
    }

    func updateNSView(_ nsView: NSColorWell, context: Context) {
        DispatchQueue.main.async {
            nsView.color = NSColor(selectedColor)
        }
    }

    func makeCoordinator() -> Coordinator {
        Coordinator(self)
    }

    class Coordinator: NSObject {
        let parent: CustomColorPicker

        init(_ parent: CustomColorPicker) {
            self.parent = parent
        }

        @objc func colorChanged(_ sender: NSColorWell) {
            parent.selectedColor = Color(sender.color)
        }
    }
}

The result looks like the following video in my SimRecorder

Quick Drop logo

Profile picture

Personal blog by An Tran. I'm focusing on creating useful apps.
#Swift #Kotlin #Mobile #MachineLearning #Minimalist


© An Tran - 2024