【问题标题】:How to allow only certain set of numbers in a UITextfield in swift 2.0如何在 swift 2.0 中只允许 UITextfield 中的某些数字集
【发布时间】:2016-01-07 07:26:32
【问题描述】:

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

【问题讨论】:

    标签: ios swift uitextfield swift2


    【解决方案1】:

    设置键盘类型为数字键盘

    添加这个

    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
    }
    

    【讨论】:

    • 感谢这对我的代码var length = (count(textField.text) + count(string) - range.length) 非常有用,并返回为return length &lt; 3 &amp;&amp; (intvalue &gt; 0 &amp;&amp; intvalue &lt;= 12) ? true : false
    • ? true : false 是多余的return 1...12 ~= intvalue
    【解决方案2】:

    您可以同时检查 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
        }
    }
    

    【讨论】:

    • 如果执行else部分并返回false,则无法清除文本或重新输入文本。
    • 我不确定你的代码,但我已经检查过了,上面的代码没有做任何事情,既不会阻止用户清除文本,也不会重新输入文本。
    • 对不起我的错误。你的代码也很好用而且很简单
    【解决方案3】:

    => 你可以像这样定义字符的限制:-

    #define NUMBERS_ONLY @"1234567890"
    
    #define  CHARACTER_LIMIT 2
    

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

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

    【讨论】:

    • 这个客观的 c 代码与上面的快速答案没有什么不同。它只是带有字符限制的目标 c 版本。 var length = (count(textField.text) + count(string) - range.length)return length &lt; 3 这是用于简单长度约束的 swift 1.2
    【解决方案4】:
    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

    【讨论】:

    • 在此函数中添加 if 条件以检查文本字段的值小于等于 12 且大于等于 1。
    • 我已经尝试过这段代码,它也允许 13 到 99。另外,如果我使用 if 条件并返回 false,我将无法再编辑文本字段,甚至退格。
    【解决方案5】:

    查看此项以设置限制数字并仅允许数字 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
    }
    

    【讨论】:

      【解决方案6】:

      我只是想根据之前的答案发布一个更简化的答案。

      在 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 中您不能写入负值。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-12-09
        • 2012-10-08
        • 2019-06-15
        • 1970-01-01
        相关资源
        最近更新 更多