Playing with Radiance
ColdFusion, iPhone SDK, Cocoa Touch, Flex, AIR, PHP, and Food. Yup… I’m all over the place…

Making the Keyboard Go Away When You Hit Return

Its amazing what you take for granted in scripting languages sometimes… for instance, when you add a UITextField to your program with no other modifications and hit run, you get a text field just as you would expect.  However, when you tap on the text field, edit it a little and hit the RETURN button, nothing happens.

This is because, on its own, a UITextField can bring up a keyboard, but the keyboard can’t dismiss itself.  In order to make this happen, you need to add some code to the delegate for this text field that tells it to resign itself as the first responder.

Here’s my current preferred way of doing this.  Lets say, you have a set of many different text fields inside of a UIViewController called “MyViewClass”.  You will need to need to state that this view controller should also act as a UITextFieldDelegate.

Go into your header file for this class (in this example, it would be MyViewClass.h) and add <UITextFieldDelegate> to the end of the @interface line, like so:

@interface MyViewClass : UIViewController <UITextFieldDelegate>

Once this is done, add the following code to the end of your MyViewClass.c just before the @end statement:

#pragma mark -
#pragma mark Text Field Delegate Methods

- (BOOL) textFieldShouldReturn:(UITextField *)textField {
[textField resignFirstResponder];
return YES;
}

Now, make sure the delegate for your UITextFields is set to MyViewClass.  If you are creating these text fields inside the code in your MyViewClass.c file, just set the delegate = self.  Otherwise, if you’re in interface builder, make sure you assign the delegate to file owner using the Text Field Connections tool.

No Responses Yet to “Making the Keyboard Go Away When You Hit Return”

Leave a Reply