如何将uitextfield字符范围限制为10位数

时间:2015-04-21 05:03:48

标签: ios objective-c iphone uitextfield

我只是想知道如何限制uitextfield范围,即我有一个文本框,我输入值10位数。如果我尝试输入超过10位数,我的文本字段不应该接受这些值。为了非常简单,我想在文本字段中只输入10位数字。

我计算出这段代码,但它对我不起作用:

- (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;
  }

9 个答案:

答案 0 :(得分:11)

要限制文本输入的长度,请实现UITextFieldDelegate的这种方法并在更改后检查文本的长度:

- (BOOL)            textField:(UITextField *)textField
shouldChangeCharactersInRange:(NSRange)range
            replacementString:(NSString *)string {
    NSString *resultText = [textField.text stringByReplacingCharactersInRange:range
                                                                   withString:string];
    return resultText.length <= 10;
}

答案 1 :(得分:5)

  

在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
}

答案 2 :(得分:3)

尝试以下仅限10个数字文字的代码。

 - (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;
    }

希望这对你有所帮助。

答案 3 :(得分:2)

Swift 3版

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
    }

答案 4 :(得分:1)

试试这个。

-(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;}

答案 5 :(得分:1)

您可以使用此...我希望它可以帮助您/

   -(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;

答案 6 :(得分:0)

我构建了一个非常好的UITextField子类来限制输入字段的字符数。你走了!:

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
         }
    }
}

这取决于String的下标。这也是:

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
        }
    }
}

答案 7 :(得分:0)

我根据Oxcug给出的答案构建了一个子类,而无需在String文件中创建扩展名,并且可以从storyboard和swift文件中设置最大字符长度。:

@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)
            }
        }
    }
}

答案 8 :(得分:0)

最佳解决方案:

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        
        return range.location < 10 //Here 10 is your character limit
    }