0

I have TextView.In TextView i have to set maximum 160 character to TextView including space.If i click return the keyboard should go down.I have coding.It works after enter 160 character only.So if i click retun, immeadiately it should go down and it should not be after 160 character including space.Even if i click return after entering "how are you?" in the text view,the keyboard should hide.

My Coding is

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

{   

   //First type for space

    /* 
     return txtviewAsk.text.length + (text.length - range.length) <= 160;
     [txtviewAsk resignFirstResponder];
    */

   //Second type with correct method

     NSUInteger newLength = (textView.text.length - range.length) + text.length;
     if(newLength <= MAX_LENGTH)
     {
        //[txtview resignFirstResponder];
          return YES;
     } 
     else 
     {
        NSUInteger emptySpace = MAX_LENGTH - (textView.text.length - range.length);
        textView.text = [[[textView.text substringToIndex:range.location]
                      stringByAppendingString:[text substringToIndex:emptySpace]]

                     stringByAppendingString:[textView.text substringFromIndex:(range.location + range.length)]];


        [txtviewAsk resignFirstResponder];
        return NO;

        }


}
user3182143
  • 9,459
  • 3
  • 32
  • 39
  • checkout this answer http://stackoverflow.com/questions/703754/how-to-dismiss-keyboard-for-uitextview-with-return-key – Divya Jan 22 '14 at 09:18

2 Answers2

0
Add return no to the below of the if condition.
if(newLength <= MAX_LENGTH)
{
    if ( [textView.text isEqualToString:@"\n"] ) {
            [textView resignFirstResponder];
             return NO;
           }
     return YES;
}
0
-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{

    if(textView.text.length >=160)
    {
        [textView resignFirstResponder];
        return NO;

    }
    if([text rangeOfCharacterFromSet:[NSCharacterSet newlineCharacterSet]].location == NSNotFound) {
    return YES;

    }

    [textView resignFirstResponder];
    return NO;
}

Basically, the first part is to check the length and ends editing and the second part is for return key..

PS: Second part comes from this rebito's answer from here. So, credit goes to him..

Community
  • 1
  • 1
GenieWanted
  • 4,473
  • 4
  • 24
  • 35