0

I'm trying to hide the keyboard after the user clicked on the return button of the keyboard.

I'm using this function to hide it:

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range
 replacementText:(NSString *)text
{
    if ([text isEqualToString:@"\n"]) {

        [textView resignFirstResponder];

        return NO;
    }
    return YES;
}

When the textview is empty this function works but once there is a characters in the textview,nothing happens and the keyboard doesnt get hidden.

Aviv Paz
  • 1,051
  • 3
  • 13
  • 28
  • 2
    Does your code go through the `if` test? – Larme Oct 07 '14 at 16:26
  • Why would you use a text view instead of a text field if you are only going to allow one line of text? – rmaddy Oct 07 '14 at 16:28
  • You should probably be using UITextField instead. See the answer here: http://stackoverflow.com/a/704197/2708650 – Ian MacDonald Oct 07 '14 at 16:30
  • I have replicated your code and it works fine. My only thought is maybe you've declared an instance variable named `textView` and the code doesn't know whether to resign the local or instance `textView`. I added an `NSLog` statement before the `resignFirstResponder` line and it gets hit regardless of whether the text view contains other characters, or if the cursor is in the middle of the content. – Stonz2 Oct 07 '14 at 16:32
  • Yes it does go through the if . How the keyboard should resign if i let the user write more then one line? – Aviv Paz Oct 07 '14 at 16:32
  • @Stonz2 The method parameter would take precedence of an ivar with the same name. There would be no confusion. Variable scope is clearly defined with no ambiguity. – rmaddy Oct 07 '14 at 16:46
  • @AvivPaz To dismiss the keyboard for a text view on an iPhone or iPod touch you can use an `inputAccessoryView` with a button that dismisses the keyboard. – rmaddy Oct 07 '14 at 16:47
  • I assume you've set yourself up as the delegate for the UITextView – Flexicoder Oct 07 '14 at 17:11
  • yes of course , it wouldnt get to the shouldChangeTextInRange funtion if i wouldn't have. It's really weird , when i debug it , it's going through the samme process if the textview is empty or if it's not but only when it's empty , the resign works – Aviv Paz Oct 07 '14 at 17:18

2 Answers2

2

I would suggest to use [self endEditing:YES]; or self.view endEditing:YES]

Coldsteel48
  • 3,482
  • 4
  • 26
  • 43
0

Found the answer. Was my fault. I had a function which once the user finished editing i'm checking if it's empty or not. For some reason returned no instead of yes. Thanks for the help

Aviv Paz
  • 1,051
  • 3
  • 13
  • 28