A Colour Picker pretty much identical to Apple's ColorPicker (in that it uses the UIColorPickerViewController), except that this one can be presented in the way common to sheets, etc, with a bound 'isPresented' boolean var.
In Xcode:
- File ⭢ Swift Packages ⭢ Add Package Dependency...
- Use the URL https://github.com/franklynw/PresentableColorPicker
NB: All examples require
import PresentableColorPicker
at the top of the source file
It can be used directly as a view, which offers the full range of customisation options -
var body: some View {
PresentableColorPicker(isPresented: $isStandaloneColorPickerPresented) {
viewModel.paintColor = $0
}
.backgroundColor(viewModel.backgroundColor)
.disableDismissOnSelection
}
or as a modifier, which presents the default colour picker (with no customisation options) -
var body: some View {
MyView {
}
.presentableColorPicker(isPresented: $isStandaloneColorPickerPresented, Binding: $viewModel.paintColor)
}
Both of these methods allow you to specify either a binding to a Color var, or use a 'colorSelected' closure which is invoked when the colour is picked.
PresentableColorPicker(isPresented: $isStandaloneColorPickerPresented, selected: $viewModel.paintColor)
.title("Pick a colour")
If not used, the title will default to localised "Colour" (ie, if you have "Colour" in your Localizable.strings file, it will use that, otherwise just "Colour")
This might be necessary if you have (eg) a preview visible above the picker, where you can see how your selected colour looks - the user can then decide when to dismiss the picker
PresentableColorPicker(isPresented: $isStandaloneColorPickerPresented, selected: $viewModel.paintColor)
.disableDismissOnSelection
PresentableColorPicker(isPresented: $isStandaloneColorPickerPresented, selected: $viewModel.paintColor)
.backgroundColor(.lightGray)
Set the height of the picker as either a fixed height or as a proportion of the containing view's height
PresentableColorPicker(isPresented: $isStandaloneColorPickerPresented, selected: $viewModel.paintColor)
.height(.fixed(400))
or
PresentableColorPicker(isPresented: $isStandaloneColorPickerPresented, selected: $viewModel.paintColor)
.height(.proportional(0.6))
There are two NotificationCenter notifications which are sent, which are defined as static vars on Notification.Name -
- presentableColorPickerAppeared ("PresentableColorPickerAppearedNotification")
- presentableColorPickerDisappeared ("PresentableColorPickerDisappearedNotification")
These are sent as their names suggest, and there is no additional userInfo
Requires HalfASheet, which is linked. Take a look at it here
PresentableColorPicker
is available under the MIT licence