Pages

Saturday, April 24, 2010

Cocoa. Simple Controller

I hope, finally, I do understand all this story with the GUI controller in Cocoa applications. The story is short, but in the beginning, this all was complicated for me to connect my GUI controls with my code in the Interface Builder.
The scenario is simple:
1. Add new Objective-C class (everything as usual, by default it is derived from NSObject).



2. Add IBAction, as many as you need, for example, doButton, doSlider, DoMenu, etc, whatever you have in your GUI.

#import <Cocoa/Cocoa.h>


@interface MyNSController : NSObject {

}

- (IBAction)doSlider:(id)sender;
- (IBAction)doButton:(id)sender;
- (IBAction)doMenu:(id)sender;

@end




Add an implementation:
#import "MyNSController.h"


@implementation MyNSController

- (IBAction)doSlider:(id)sender
{
float value = [sender floatValue];
NSLog(@"Do Slider. Value = %f", value);
}

- (IBAction)doButton:(id)sender
{
NSLog(@"Do Button");
}

- (IBAction)doMenu:(id)sender
{
NSLog(@"Do Menu");
}

@end

3. Launch Interface Builder (double-click on MainMenu.xib file).
4. Add GUI controls (button, slider, menu, etc.)

5. in the Library choose Classes tab, find your class in the list and drag it to the MainMenu.xib document.

6. The class appears in the Inspector. You see all actions you added. Connect them with the controls.

7. Build and Run your application.

No comments:

Post a Comment