Example code programming Objective-C with Cocoa in Xcode and Interface Builder (Leopard)
3: Example: Horizontal Slider
Implementing a simple Slider control
In XCode: File->New Project->Cocoa Application
Call it: SliderApp
Next do: File->New File and choose Objective C Class.
Call the files MyNSControl.h and MyNSControl.m, code them as shown below and save. Note these are subclassed as NSControl. And that the slider will be of class NSSlider.
// MyNSControl.h // SliderApp #import <Cocoa/Cocoa.h> @interface MyNSControl : NSControl { } - (IBAction)doSlider:(id)pObj; @end // MyNSControl.m // SliderApp #import "MyNSControl.h" @implementation MyNSControl - (IBAction)doSlider:(id)pObj; { float tvarFloatvalue = [pObj floatValue]; NSLog(@"Hi there: value=%6.3f",tvarFloatvalue); } // end doSlider @end
Now bring up Interface Builder by double clicking on MainMenu.nib in the Resources section of SliderApp
Drag a Horizontal Slider onto the Window panel. Click on the Window Panel to select it.
In the Inspector chose the MyNSControl class. The action doSlider will appear in the action panel.
Interface Builder showing the Horizontal Slider and the object NSControl class in the Inspector
Choose the Connections display in the Inspector and drag from the connection circle next to the Action 'doSlider' to the slider you dragged onto the window.
You will see a label pop-up as shown in the picture below.
Let go the mouse button and the display will change as shown.
Interface Builder showing linking action to Horizontal Slider (NSSlider)
Click on the Horizontal Slider to select it.
Choose the Control Attributes display in the Inspector.
Tick the enabled and continuous mode check boxes. Set the value range from 0 to 100.
Interface Builder showing link with Horizontal Slider (NSSlider)
Save Interface Builder.
Return to XCode. Choose Run->Console. Now Build and Run.
As you move the slider a sequence of 'Hi There value = ....' will appear in the Console log.
Interface Builder showing Control Attributes of Horizontal Slider (NSSlider)
If you want to download the code
Click the Download Link to obtain 003-SliderAppThumb.zip file of this whole OS X 10.5 Leopard program.