1

I'm a beginner iOS developer. I'm working on an application in which there's a textview but the associated keyboard is not dismissing when I click the 'return' or 'enter' key.

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    if([text isEqualToString:@"\n"])
    {
        [txtView resignFirstResponder];
        return NO;
    }

    return YES;
}

Any suggestions are welcome.

  • 1
    You should expand on your previous question on this matter (http://stackoverflow.com/questions/10429077/how-can-i-dismiss-keyboard-when-i-click-enter-in-textview) rather than create a new question using the code unchanged. –  May 07 '12 at 08:30

1 Answers1

1

This is taken from Niels Hansen : Dismiss iphone keyboard

here is a couple of things you need to remember. The number #1 part developers forget to set is the delegate of the textField.

If you are using the Interface Builder, you must remember that you need to set the delegate of the textField to the file Owner.

If you are not using Interface Builder then make sure you set the delegate of the textfield to self. I also include the returnType. For Example if the textField was called gameField:

gameField.delegate = self;
gameField.returnKeyType = UIReturnKeyDone;

You must also implement the UITextFieldDelegate for your ViewController.

@interface YourViewController : UIViewController <UITextFieldDelegate> 

Finally you need to use the textFieldShouldReturn method and call

[textField resignFirstResponder]

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

All your textFields will use this same method so you only need to have this setup once. As long as the delegate is set for the textField, the UITextFieldDelegate is implemented for the interface, you add the textFieldShouldReturn method and call the resignFirstResponder your set

Community
  • 1
  • 1
MJB
  • 3,934
  • 10
  • 48
  • 72