Set the maximum character length of a UITextField

前端 未结 30 1694
难免孤独
难免孤独 2020-11-22 02:27

How can I set the maximum amount of characters in a UITextField on the iPhone SDK when I load up a UIView?

相关标签:
30条回答
  • 2020-11-22 02:55

    The following code is similar to sickp's answer but handles correctly copy-paste operations. If you try to paste a text that is longer than the limit, the following code will truncate the text to fit the limit instead of refusing the paste operation completely.

    - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
        static const NSUInteger limit = 70; // we limit to 70 characters
        NSUInteger allowedLength = limit - [textField.text length] + range.length;
        if (string.length > allowedLength) {
            if (string.length > 1) {
                // get at least the part of the new string that fits
                NSString *limitedString = [string substringToIndex:allowedLength];
                NSMutableString *newString = [textField.text mutableCopy];
                [newString replaceCharactersInRange:range withString:limitedString];
                textField.text = newString;
            }
            return NO;
        } else {
            return YES;
        }
    }
    
    0 讨论(0)
  • 2020-11-22 02:57

    To complete August answer, an possible implementation of the proposed function (see UITextField's delegate).

    I did not test domness code, but mine do not get stuck if the user reached the limit, and it is compatible with a new string that comes replace a smaller or equal one.

    -(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
        //limit the size :
        int limit = 20;
        return !([textField.text length]>limit && [string length] > range.length);
    }
    
    0 讨论(0)
  • 2020-11-22 03:00

    This is the correct way to handle max length on UITextField, it allows the return key to exit the resign the textfield as first responder and lets the user backspace when they reach the limit

    - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    int MAX_LENGHT = 5;
        if([string isEqualToString:@"\n"])
        {
            [textField resignFirstResponder];
            return FALSE;
        }
        else if(textField.text.length > MAX_LENGHT-1)
        {
            if([string isEqualToString:@""] && range.length == 1)
            {
                return TRUE;
            }
            else
            {
                return FALSE;
            }
        }
        else
        {
            return TRUE;
        }
    }
    
    0 讨论(0)
  • 2020-11-22 03:00

    I have open sourced a UITextField subclass, STATextField, that offers this functionality (and much more) with its maxCharacterLength property.

    0 讨论(0)
  • 2020-11-22 03:01

    While the UITextField class has no max length property, it's relatively simple to get this functionality by setting the text field's delegate and implementing the following delegate method:

    Objective-C

    - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
        // Prevent crashing undo bug – see note below.
        if(range.length + range.location > textField.text.length)
        {
            return NO;
        }
            
        NSUInteger newLength = [textField.text length] + [string length] - range.length;
        return newLength <= 25;
    }
    

    Swift

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        
        let currentCharacterCount = textField.text?.count ?? 0
        if range.length + range.location > currentCharacterCount {
            return false
        }
        let newLength = currentCharacterCount + string.count - range.length
        return newLength <= 25
    }
    

    Before the text field changes, the UITextField asks the delegate if the specified text should be changed. The text field has not changed at this point, so we grab it's current length and the string length we're inserting (either through pasting copied text or typing a single character using the keyboard), minus the range length. If this value is too long (more than 25 characters in this example), return NO to prohibit the change.

    When typing in a single character at the end of a text field, the range.location will be the current field's length, and range.length will be 0 because we're not replacing/deleting anything. Inserting into the middle of a text field just means a different range.location, and pasting multiple characters just means string has more than one character in it.

    Deleting single characters or cutting multiple characters is specified by a range with a non-zero length, and an empty string. Replacement is just a range deletion with a non-empty string.

    A note on the crashing "undo" bug

    As is mentioned in the comments, there is a bug with UITextField that can lead to a crash.

    If you paste in to the field, but the paste is prevented by your validation implementation, the paste operation is still recorded in the application's undo buffer. If you then fire an undo (by shaking the device and confirming an Undo), the UITextField will attempt to replace the string it thinks it pasted in to itself with an empty string. This will crash because it never actually pasted the string in to itself. It will try to replace a part of the string that doesn't exist.

    Fortunately you can protect the UITextField from killing itself like this. You just need to ensure that the range it proposes to replace does exist within its current string. This is what the initial sanity check above does.

    swift 3.0 with copy and paste working fine.

    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
            let str = (textView.text + text)
            if str.characters.count <= 10 {
                return true
            }
            textView.text = str.substring(to: str.index(str.startIndex, offsetBy: 10))
            return false
        }
    

    Hope it's helpful to you.

    0 讨论(0)
  • 2020-11-22 03:03

    Swift 4

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        guard let text = textField.text else { return true }
        let newLength = text.count + string.count - range.length
        return newLength <= 10
    }
    
    0 讨论(0)
提交回复
热议问题