如何在swift 2.0中只允许UITextfield中的某些数字集

时间:2016-01-07 07:26:32

标签: ios swift uitextfield swift2

我有一个UITextField,其中我将月份数作为输入。我成功地将UITextField中的字符数限制为2。但我希望用户只输入1 to 12的值,而不是其他值。当用户键入数字时,必须同时进行此操作,即func textField(textField: UITextField!, shouldChangeCharactersInRange range: NSRange, replacementString string: String!) -> Bool。如果我使用简单的if条件检查每个字符并在else部分返回false,则textfield不允许我使用clear或重新键入任何其他字符。谁来帮帮我。

6 个答案:

答案 0 :(得分:3)

您可以通过检查shouldChangeCharactersInRange中的TextField值来同时执行此操作。

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    let inputStr = textField.text?.stringByAppendingString(string)
    let inputInt = Int(inputStr!)
    if inputInt > 0 && inputInt < 13 {
        return true
    } else {
        return false
    }
}

答案 1 :(得分:3)

将键盘类型设置为数字键盘

添加此

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

    if let text = textField.text {

        let newStr = (text as NSString)
            .stringByReplacingCharactersInRange(range, withString: string)
        if newStr.isEmpty {
            return true
        }
        let intvalue = Int(newStr)
        return (intvalue >= 0 && intvalue <= 12)
    }
    return true
}

答案 2 :(得分:2)

=&GT;你可以像这样定义char的限制: -

#define NUMBERS_ONLY @"1234567890"

#define  CHARACTER_LIMIT 2

=&GT;并且基于定义限制字符,您可以使用并尝试以下方法: -

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

        NSUInteger newLength = [textField.text length] + [string length] - range.length;

        NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:NUMBERS_ONLY] invertedSet];

        NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];

        return (([string isEqualToString:filtered])&&(newLength <= CHARACTER_LIMIT));

    }

答案 3 :(得分:0)

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

        // Create an `NSCharacterSet` set which includes everything *but* the digits
        let inverseSet = NSCharacterSet(charactersInString:"0123456789").invertedSet

        // At every character in this "inverseSet" contained in the string,
        // split the string up into components which exclude the characters
        // in this inverse set
        let components = string.componentsSeparatedByCharactersInSet(inverseSet)

        // Rejoin these components
        let filtered = components.joinWithSeparator("")  // use join("", components) if you are using Swift 1.2

        // If the original string is equal to the filtered string, i.e. if no
        // inverse characters were present to be eliminated, the input is valid
        // and the statement returns true; else it returns false
        return string == filtered

}

请参阅此链接 - Limit UITextField input to numbers in Swift

答案 4 :(得分:0)

选中此项以设置限制数字,仅允许数字0到9。

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    if textField == mobileNumber {
        let aSet = NSCharacterSet(charactersIn:"0123456789").inverted
        let compSepByCharInSet = string.components(separatedBy: aSet)
        let numberFiltered = compSepByCharInSet.joined(separator: "")
        let length = (mobileNumber.text?.count)! + string.count - range.length
        return string == numberFiltered && length <= LIMIT
    }else if textField == userType {
        return false
    }
    return true
}

答案 5 :(得分:0)

我只想在以前的答案的基础上发布更简化的答案。

在Swift 5.1上进行了测试

考虑到您已经设置了textField.keyboardType = .numberPad,则可以执行以下操作:

 func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        guard let text = textField.text else {
            return true
        }
        let newStr = (text as NSString).replacingCharacters(in: range, with: string)

        guard let intValue = Int(newStr) else {
            return true
        }
        return intValue <= maxNumber // maxNumber: replace with your max number
    }

您不需要验证intValue大于或等于0,因为在numberPad中您不能写负值。