0

I am working iOS app. In that app i have textfields and textviews. My requirment is dismiss keyboard if user tapped space button twice even if starting of the text or ending of the text. I tried with following code

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {

    NSLog(@"textView.text %@",textView.text);
    NSUInteger newLength = (textView.text.length - range.length) + text.length;
    //for white space starting
    NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:@" "] invertedSet];
    NSString *filtered = [[text componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
 
    if([text isEqualToString:@"\n"]) {
        [sendMsgTextView resignFirstResponder];
     //   [self animateTextView:textView up:NO];
        return NO;
       }
    if ([textView.text isEqualToString:filtered]) {
           [sendMsgTextView resignFirstResponder];
        return NO;
    }
 return YES;
}

But the problem is its restricting the starting of the text only. If i entered text and the tapped space multiple times, the keyboard is not dismissing or not restricting. Could any one has idea about this issue. If so, please give your valuable suggestions.

2 Answers2

1

Please use the solution below..

in .h file

@property (nonatomic,retain)NSString *spaceStr;

in .m file

** -(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {

if([text isEqualToString:@"\n"]) {
    [self.txtView1 resignFirstResponder];
    //   [self animateTextView:textView up:NO];
    return NO;
}
if ([[self.spaceStr stringByAppendingString:text] isEqualToString:@"  "]) {
    self.spaceStr=@"";
    [self.txtView1 resignFirstResponder];
    return NO;
}
self.spaceStr=text;

return YES;

}

0

I used following code using following link

- (BOOL) textView:(UITextView*)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString*)text
{

 //for restricting the double space for before entering text as well as after entering the text
    if ( (range.location > 0 && [text length] > 0 &&
          [[NSCharacterSet whitespaceCharacterSet] characterIsMember:[text characterAtIndex:0]] &&
          [[NSCharacterSet whitespaceCharacterSet] characterIsMember:[[textView text] characterAtIndex:range.location - 1]]) )

    {
        //Manually replace the space with your own space, programmatically
        textView.text = [textView.text stringByReplacingCharactersInRange:range withString:@""];

        //Make sure you update the text caret to reflect the programmatic change to the text view
        textView.selectedRange = NSMakeRange(range.location+1, 0);

        //Tell Cocoa not to insert its space, because you've just inserted your own
        return NO;
    }
}

and the link is iPhone: Disable the "double-tap spacebar for ." shortcut?

Community
  • 1
  • 1