CocoaLearning pathSliderThe Color Sorting example is the content to be introduced in this article. This development instance is the same as dragging the slide with the mouse, adjusting the three primary color values, thus changing the Final SynthesisColor. New users can use this exercise for NSTextField, NSSlider, NSColor, and NSObject.
1. Create a Cocoa project SliderColor
You need to drag a Text FieldWidget, And four HorizontalSlider ControlTo the window. Text Field is used for display.Color, HorizontalSliderThey are alpha, red, green, and blue. Set the Text Field attribute to read-only (Enabled), Background to black, and HorizontalSliderThe Minimum value (Minimum) is set to 0, the maximum value (Miximum) is 1, and the Continuous check box is selected (this is to change the value when dragging), the Current alpha value (Current) is 1, the other current values are all 0,
2. Create a Controller (NSObject)
Drag an NSObject named ColorController and create Outlets as follows:
- AlphaSlider
- BlueSlider
- ColorField
- GreenSlider
- RedSlider
- Create Actions as follows:
- SetAlpha
- SetBlue
- SetGreen
- SetRed
BIND (Associate) The created Outlets and Actions controls to the window and save the ColorController to the project.
3. write code in ColorController
You need to add a float type variable in ColorController. h to store the Slider value and a void type updateColor method to update the color. The final code is as follows:
- #import <Cocoa/Cocoa.h>
-
- @interface ColorController : NSObject {
- IBOutlet NSSlider *alphaSlider;
- IBOutlet NSSlider *blueSlider;
- IBOutlet NSTextField *colorField;
- IBOutlet NSSlider *greenSlider;
- IBOutlet NSSlider *redSlider;
-
- float redValue;
- float blueValue;
- float greenValue;
- float alphaValue;
- }
- - (IBAction)setAlpha:(id)sender;
- - (IBAction)setBlue:(id)sender;
- - (IBAction)setGreen:(id)sender;
- - (IBAction)setRed:(id)sender;
- - (void)updateColor;
- @end
Add the updateColor method to ColorController. m to convert the RGB color and set the background color of the Text Field. Call updateColor by dragging. The complete code is as follows:
- # Import "ColorController. h"
- @ Implementation ColorController
- -(IBAction) setAlpha :( id) sender {
- [Self updateColor]; // call the updateColor Method
- }
- -(IBAction) setBlue :( id) sender {
- [Self updateColor];
- }
- -(IBAction) setGreen :( id) sender {
- [Self updateColor];
- }
- -(IBAction) setRed :( id) sender {
- [Self updateColor];
- }
- -(Void) updateColor {
- // Obtain the RGB and Alpha values and assign them to the variables.
- RedValue = [