I’m writing this quick little tutorial because I could not find a single source for what I wanted to do, but found myself reading multiple docs and putting it together. So, here we go:
Having Return Execute an Action for an NSTextField
Part 1: Quick Setup
- Create a new Cocoa Application named TextFieldTutorial. (I am not going to go into much detail about this, as there are better beginning tutorials out there if you need it).
- Open your MainMenu.xib and create your UI. Create two NSTextFields one for input and the other for output. Set these up visually however you’d like.
- Add a new File that extends NSObject and name it TextFieldTutorialController (be sure to generate the .h file as well).
Part Two: Writing the Code
There are a couple set-up things we need to add to the code. We’ll need to add the references to the two NSTextFields in our controller’s header file. Make sure these are tagged by IBOutlet to allow Interface Builder to know that it can hook into it.
Additionally, create the method definition for hitting enter. You code should look something like:
#import <Cocoa/Cocoa.h>
@interface TextFieldTutorialController : NSObject {
IBOutlet NSTextField* inputField;
IBOutlet NSTextField* outputField;
}
-(IBAction)userHitEnter:(id)sender;
@end
Next, all we have to do is fill in the body for userHitEnter. It will be a rather simplistic method:
@implementation TextFieldTutorialController
-(IBAction)userHitEnter:(id)sender {
[outputField setStringValue:[inputField stringValue]];
}
@end
Yep, that’s it. This is easy.
Part Three: Hooking Everything Together
Now, that our code is ready, we need to hook the UI to the controller. Go back to Interface Builder and add a new Object to your NIB file.

Change the type of NSObject to TextViewTutorialController:

Now, hook up the outlets of TextViewTutorialController to the two NSTextViews. Do this for both inputText and outputText.

Next, we need to set up our inputText object. First, we will set it to only call an action on Enter. Otherwise, we would be making a message call on every press of the keyboard (feel free to leave it like this if you want to experiment).

Then the last thing we need to do it set the Sent Actions selector of the Input NSTextField to our controller and select the userHitEnter method.


That’s it! Build and Run, and you should be able to type anything in the inputText area and hit enter, this will update the outputText.



