How to allow only certain set of numbers in a UITe

2020-02-13 02:21发布

I am having a UITextField in which i get the month number as input. I am successful in limiting the no of characters to 2 in the UITextField. But i want users to enter only the values from 1 to 12 and none other than that. This has to be done simultaneously when the user types the numbers i.e in func textField(textField: UITextField!, shouldChangeCharactersInRange range: NSRange, replacementString string: String!) -> Bool. If i use a simple if condition to check the each character and return false in else part the textfield won't allow me to use clear or retype any other character. someone help me.

6条回答
戒情不戒烟
2楼-- · 2020-02-13 02:59
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

}

see this link-- Limit UITextField input to numbers in Swift

查看更多
Animai°情兽
3楼-- · 2020-02-13 03:03

=> you can Define limite of char like this:-

#define NUMBERS_ONLY @"1234567890"

#define  CHARACTER_LIMIT 2

=> and based on define limit char you can use and try it below method :-

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

    }
查看更多
The star\"
4楼-- · 2020-02-13 03:04

You can do it simultaneously by checking the TextField value inside shouldChangeCharactersInRange.

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
    }
}
查看更多
仙女界的扛把子
5楼-- · 2020-02-13 03:04

Check out this to set Limit the numbers and allow only numbers 0 to 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
}
查看更多
Luminary・发光体
6楼-- · 2020-02-13 03:06

I just want to post a more simplified answer based on the previous answers.

Tested on Swift 5.1

Considering that you already set textField.keyboardType = .numberPad, then you can do the following:

 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
    }

You dont´need to validate that intValue is greater or equal to 0 because in numberPad you can NOT write negative values.

查看更多
小情绪 Triste *
7楼-- · 2020-02-13 03:22

Set keyboard type as Number Pad

add this

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
}
查看更多
登录 后发表回答