Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to limit uitextfield character range upto 10 digit

I just want to know how to limit uitextfield range, i.e I have one textbox in that I enter values 10 digit. If I try to type more than 10 digit my textfield should not accept the values. To be very simple I want only 10 digit should be enter in the textfield.

I work out this code but its not worked for me:

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

NSUInteger oldLength = [textField.text length];
NSUInteger replacementLength = [string length];
NSUInteger rangeLength = range.length;

NSUInteger newLength = oldLength - rangeLength + replacementLength;

BOOL returnKey = [string rangeOfString: @"\n"].location != NSNotFound;

return newLength <= MAXLENGTH || returnKey;
  }
like image 366
Anand - Avatar asked Apr 21 '15 05:04

Anand -


3 Answers

To limit a text input's length implement this method of UITextFieldDelegate and check a text's length after changing:

- (BOOL)            textField:(UITextField *)textField
shouldChangeCharactersInRange:(NSRange)range
            replacementString:(NSString *)string {
    NSString *resultText = [textField.text stringByReplacingCharactersInRange:range
                                                                   withString:string];
    return resultText.length <= 10;
}
like image 98
Vlad Avatar answered Oct 21 '22 03:10

Vlad


In Swift 3.0

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

    let charsLimit = 10

    let startingLength = textField.text?.characters.count ?? 0
    let lengthToAdd = string.characters.count
    let lengthToReplace =  range.length
    let newLength = startingLength + lengthToAdd - lengthToReplace

    return newLength <= charsLimit
}
like image 44
Ashok R Avatar answered Oct 21 '22 03:10

Ashok R


Try below code that is restricted to 10 digital text.

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

        NSInteger length = [textField.text length];
        if (length>9 && ![string isEqualToString:@""]) {
            return NO;
        }

        // This code will provide protection if user copy and paste more then 10 digit text

       dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
           if ([textField.text length]>10) {
                textField.text = [textField.text substringToIndex:10];

            }
       });


        return YES;
    }

Hope this help you.

like image 3
Jatin Patel - JP Avatar answered Oct 21 '22 04:10

Jatin Patel - JP