With iOS 14 we can use the new UIColorPickerViewController
to let user select color. In this post let's briefly check how to use it. You of course need the new Xcode 12 to be able to try this example.
Showing the color picker
The new UIColorPickerViewController
works basically in the same way like other pickers and pre-made controllers. We create an instance, set ourselves as a delegate
and present
the picker like so:
let picker = UIColorPickerViewController()
picker.delegate = self
present(picker, animated: true, completion: nil)
Note that you should not wrap the picker in UINavigationController
I tried it and got very strange behaviour with missing background. Also since the picker has its own navbar I think that is the indication it should not be used with UINavigationController
.
Once you present the controller, you get UI like this:
There are three ways how to pick a color with the option to also select opacity. This can be customized with the supportsAlpha
property. If set to false
you cannot change opacity and cannot select color with alpha component. So far that is the only customization we have.
Implementing the delegate
To get notified about user's color selection we need to implement the UIColorPickerViewControllerDelegate
. These are two methods. One informs us about new color selection and the other about user closing the picker.
The basic implementation could look like this:
func colorPickerViewControllerDidFinish(_ viewController: UIColorPickerViewController) {
dismiss(animated: true, completion: nil)
}
func colorPickerViewControllerDidSelectColor(_ viewController: UIColorPickerViewController) {
let color = viewController.selectedColor
}
And that is our first look at UIColorPickerViewController
.
Top comments (0)