Execute code in objective-c when enter key is pressed?

| | August 11, 2015

I’m working on an Objective-C Xcode project in Xcode 6. I have a textfield and a button that checks what’s in the textfield when pressed.

However, I would like the code to run when enter key is pressed instead of the submit button.

I have seen that you can set the key equivalent for a button in Xcode however this option doesn’t appear to feature in Xcode 6.

4 Responses to “Execute code in objective-c when enter key is pressed?”

  1. AddWeb Solution Pvt Ltd on November 30, -0001 @ 12:00 AM

    Follow the below steps.

    1. Set delegate of UITExtfield
    2. Add tag value if there are multiple textfield
    3. Now call the delegate method of UITextfield same as below.


    optional func textFieldShouldReturn(_ textField: UITextField) -> Bool 

    Hope this helps!

  2. Rohit suvagiya on November 30, -0001 @ 12:00 AM

    First make your file delegate for UITextField and then add this method to your code ..

    -(BOOL) textFieldShouldReturn:(UITextField *)textField
       [textField resignFirstResponder];
       return YES;
  3. Implement textField delegate method.

    -(BOOL)textFieldShouldReturn:(UITextField *)textField
         [self callYourCodeWantToExecute];
         //return YES; // want to hide keyboard
         //return NO; // want keyboard
  4. You need to:

    1. Set delegate for textField
    2. In your delegate object handle -(BOOL)textFieldShouldReturn:(UITextField *)textField i.e. do what you need to do when return pressed and return YES if you want to text field get return NO if you don’t want to handle return for text field.

Leave a Reply