7

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;
  }
JSON C11
  • 11,272
  • 7
  • 78
  • 65
Anand -
  • 291
  • 2
  • 3
  • 11
  • 1
    possible duplicate of [Set the maximum character length of a UITextField](http://stackoverflow.com/questions/433337/set-the-maximum-character-length-of-a-uitextfield) – Apoorv Apr 21 '15 at 05:52
  • [This][1] is the best solution I found. http://stackoverflow.com/questions/433337/set-the-maximum-character-length-of-a-uitextfield [1]: http://stackoverflow.com/questions/433337/set-the-maximum-character-length-of-a-uitextfield – Kaey Apr 21 '15 at 11:39

9 Answers9

11

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;
}
Vlad
  • 7,199
  • 2
  • 25
  • 32
5

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
}
Ashok R
  • 19,892
  • 8
  • 68
  • 68
3

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.

Jatin Patel - JP
  • 3,725
  • 2
  • 21
  • 43
2

Swift 3 Version

func textField(_ textField: UITextField, shouldChangeCharactersIn range:NSRange, replacementString string: String) -> Bool
    {
        let currentCharacterCount = textField.text?.characters.count ?? 0
        if (range.length + range.location > currentCharacterCount){
            return false
        }
        let newLength = currentCharacterCount + string.characters.count - range.length
        return newLength <= 10
    }
Milap Kundalia
  • 1,566
  • 1
  • 16
  • 24
1

Try this.

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
if(range.length + range.location > textField.text.length)
{
    return NO;
}

NSUInteger newLength = [textField.text length] + [string length] - range.length;
return (newLength > 10) ? NO : YES;}
Vamshi Krishna
  • 979
  • 9
  • 19
1

You can use this...i hope it will help you/

   -(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
    {
       int lenght1 = code.text.length - range.length + string.length;
    if (textField.text.length >= 4 && range.length == 0)
          return NO;
0

I built a really nice subclass of UITextField to limit the number of characters inputted into a field. Here you go!:

public class NumberFormattedTextField : UITextField {
    @IBInspectable public var maximumCharacters = 10 {
         didSet {
             format()
        }
    }

    public override func awakeFromNib() {
         format()
         addTarget(self, action: "format", forControlEvents: .EditingChanged)
    }

    func format() {
         let len = text.lengthOfBytesUsingEncoding(NSUTF8StringEncoding)
         // truncate for max characters if needed
         if len > maximumCharacters {
             text = text[1...maximumCharacters] // pulls in the last entered character and drops the first one off to preserve length
         }
    }
}

This depends on a subscript for String. Here's that too:

public extension String {
    public subscript (r: Range<Int>) -> String? {
        let l = self.lengthOfBytesUsingEncoding(NSUTF8StringEncoding)
        if r.startIndex <= l && r.endIndex <= l {
            return substringWithRange(Range(start: advance(startIndex, r.startIndex), end: advance(startIndex, r.endIndex)))
        } else {
            return nil
        }
    }
}
Oxcug
  • 6,524
  • 2
  • 31
  • 46
0

I have build a subclass based on the answer given by Oxcug without the need for creating an extension in String file and max characters length can be set from storyboard and from swift file as well.:

@IBDesignable class CustomTextField: UITextField {
    @IBInspectable var maximumCharacters: Int = 80 {
        didSet {
            limitCharacters()
        }
    }
    override func awakeFromNib() {
        super.awakeFromNib()
        limitCharacters()
        addTarget(self, action: #selector(CustomTextField.limitCharacters), for: .editingChanged)
    }

    func limitCharacters() {
        guard text != nil else {
            return
        }
        if (text?.characters.count)! > maximumCharacters {
            if let range = text?.index(before: (text?.endIndex)!) {
                text = text?.substring(to: range)
            }
        }
    }
}
0

Best Solution:

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        
        return range.location < 10 //Here 10 is your character limit
    }
Anand Gautam
  • 2,541
  • 3
  • 34
  • 70