Skip to content

Instantly share code, notes, and snippets.

@iliaskarim
Created April 22, 2024 07:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iliaskarim/d379c42afa515db8d16090cb8bfdf7ba to your computer and use it in GitHub Desktop.
Save iliaskarim/d379c42afa515db8d16090cb8bfdf7ba to your computer and use it in GitHub Desktop.
import SwiftUI
struct ResolvedColorPicker: View {
@Environment(\.self) var environment
@Binding private var selection: Color.Resolved
private let supportsOpacity: Bool
private let titleKey: LocalizedStringKey
init(_ titleKey: LocalizedStringKey, selection: Binding<Color.Resolved>, supportsOpacity: Bool = true) {
_selection = selection
self.supportsOpacity = supportsOpacity
self.titleKey = titleKey
}
var body: some View {
ColorPicker(titleKey, selection: .init {
Color(red: Double($selection.wrappedValue.red),
green: Double($selection.wrappedValue.green),
blue: Double($selection.wrappedValue.blue))
} set: { color in
selection = color.resolve(in: environment)
}, supportsOpacity: supportsOpacity)
}
}
struct ContentView: View {
@State private var resolvedColor = Color.Resolved(red: 0.0, green: 0.0, blue: 0.0, opacity: 0.0)
var body: some View {
VStack {
ResolvedColorPicker("Select your favorite color", selection: $resolvedColor)
Text("Red: \(resolvedColor.red)")
Text("Green: \(resolvedColor.green)")
Text("Blue: \(resolvedColor.blue)")
Text("Opacity: \(resolvedColor.opacity)")
}.padding()
}
}
#Preview {
ContentView()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment