DEV Community

CobraDJC
CobraDJC

Posted on

color picker app

In lesson 17 we are learning how to connect your code to the views and controls created in the storyboard. There are 2 kinds of connections between storyboards and code. The first one is an outlet. Outlets connect variables in your code to objects in the storyboard, so you can access those objects within your code. The second one is actions. Actions connect controls like switches and buttons to methods in your code, so tapping a button will run a particular method. We are going to use outlets and actions to create an app that generates colors by mixing red, green, and blue. We add a view from the object library and control-drag from the view into the code and call it colorView. When you use ColorView in the ViewController.swift code, you are referring to the view you’ve just added to the storyboard. You can use the connections inspector on the right side of the screen to check all of your actions and outlets. If something is not connected you will see an open circle. If there is an error where a connection is incorrect, the app will crash. Next is adding switches to change the color of the view by connecting the code to the switch. We then continue to make multiple switches with multiple actions, one for a different color, and when the switch is toggled, it adds that color component to the view. Make sure they are all connected to the view and its switch changed in the connection’s inspector. Finally, we are adding sliders to give better control of what color is displayed. Find the sliders in the object library and apply one for each switch. Control-drag the sliders and call the action slider changed and make sure all 3 are connected. Next is adding a reset button to the bottom of the screen which can be found in the object library. Select it and place it on the bottom, changing its name to reset. The reset button will set the value of each slider to 1 and the isOn property of each switch to false. Finally, we can polish the interface which is basically adding colors and other aesthetics to the interface of the app. Select the switches and change the on-tint color to match the color that it changes. Do the same with the slider’s min track color. This makes the purpose of the switches and sliders clearer. Now we add a border to the color view by specifying a border width, corner radius, and border color. The last thing to do is to create a function that disables the sliders unless the switch is on.

Top comments (0)