Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove the last character typed in UItextfield

I need to remove the last character if the textfield length exceeds 100,I used the following code:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if(textfield.text.length>=100)
    {
        NSString *text;
        textField.text=text;
        NSString *newString = [text substringToIndex:[text length]-1];
        textField.text=newString;
    }
    return YES;
}

But it just erases the whole text.

like image 722
nithin Avatar asked Mar 23 '12 11:03

nithin


4 Answers

You erase the whole text because of this line:

textField.text=text; // text is nil here

What you wanted to do is more likely the following:

NSString *text = textField.text;
like image 133
sch Avatar answered Nov 07 '22 03:11

sch


- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {

      if(textfield.text.length>=100)
     {
         NSString *text;
         text =[[textField text] stringByAppendingString:string];
         NSString *newString = [text substringToIndex:[text length]-1];

         textField.text=newString;
     }
     return YES;

 }

Paste the code may solve your issue

like image 24
Kuldeep Avatar answered Nov 07 '22 03:11

Kuldeep


In iOS 5 or later:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if([textField.text length] >= 100)
    {
        [textField deleteBackward];
    }
}
like image 3
TheTiger Avatar answered Nov 07 '22 02:11

TheTiger


try with the below code

 - (BOOL)textView:(UITextView *)aTextView shouldChangeTextInRange:(NSRange)aRange replacementText:(NSString *)aText {

    NSString* newText = [textView.text stringByReplacingCharactersInRange:aRange withString:aText];

    // CGSize strSize = [newText sizeWithFont:textView.font constrainedToSize:CGSizeMake(200, 10000) lineBreakMode:UILineBreakModeWordWrap];

   if([newText length] > 100)
   {
       return NO; // can't enter more text
   }
   else
      return YES; // let the textView know that it should handle the inserted text
}
like image 2
Hiren Avatar answered Nov 07 '22 03:11

Hiren