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.
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
The ColorPicker from SwiftUI is so limited, so I use NSColorWell instead pic.twitter.com/eFtKrMS3Kk
— An Tran (@antranapp) November 9, 2024