Learn how to create a Color Picker in Swift

Color Picker Swift

Recently I have created a custom color picker for the needs of one iOS app that I have developed, and now I will show you how it works.

Before we start you can download the file from here, and import the file into the project.

 

I made it as simple as possible to reuse, so let’s start with the class implementation first:

class ViewController: UIViewController,colorDelegate {
    @IBOutlet var colorPicker: ColorPicker!
    @IBOutlet var colorView: UIView!

    override func viewDidLoad() {
        super.viewDidLoad()
        colorPicker.delegate = self;
    }
    func pickedColor(color: UIColor) {
        //delegate method that intercepts the 
        colorView.backgroundColor = color;
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

As we can see in the snippet you need to call the delegate method pickedColor(color: UIColor) which will return you the picked color. You can pick the color with touch or drag gestures.

 

Then let’s continue with the interface builder:

  1. Create a UIView and connect with the outlet
  2. Assign the ColorPicker class as a custom class to the newly created UIView
  3. Create one more view (the yellow one) so you can check the color changes.

 

Screen Shot 2016-05-28 at 23.30.04

 

 

At the end, here is a video representation how it should work: 

Leave a Reply

Your email address will not be published. Required fields are marked *