【问题标题】:Limit UITextField input to numbers in Swift将 UITextField 输入限制为 Swift 中的数字
【发布时间】:2015-01-28 16:43:52
【问题描述】:

如何在 Swift 中将用户的 TextField 输入限制为数字?

【问题讨论】:

标签: ios swift xcode cocoa-touch uitextfield


【解决方案1】:

第一个你必须继承你自己的 UITextViewDelegate 类 类

class ViewController: UIViewController, UITextViewDelegate {

第二次添加 IBOutlet

@IBOutlet weak var firstName: UITextField!

第三你必须确保这个对象正在使用

override func viewDidLoad() {
        super.viewDidLoad()
   firstName.delegate = self
}


func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    if textField == firstName {
                let allowedCharacters = "1234567890"
                let allowedCharacterSet = CharacterSet(charactersIn: allowedCharacters)
                let typedCharacterSet = CharacterSet(charactersIn: string)
                let alphabet = allowedCharacterSet.isSuperset(of: typedCharacterSet)
                let Range = range.length + range.location > (fnameTF.text?.count)!

        if Range == false && alphabet == false {
            return false
        }


        let NewLength = (fnameTF.text?.count)! + string.count - range.length
        return NewLength <= 10


      } else {
        return false
    }
  }

【讨论】:

  • 看起来不错?但是这个“fnameTF.text?.count”又指的是什么?并且错过了最终回报?
  • fnameTF 是一个 textField 并且 fnameTF.text?.count 表示我们正在计算 textField 字符。 @user3069232
  • 好的,所以@IBOutlet firstName 实际上叫fnameTF?
【解决方案2】:

对于任何寻求简短答案的人,我发现this 非常有用。

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    // remove non-numerics and compare with original string
    return string == string.filter("0123456789".contains)
}

适用于 XCode 10.1、Swift 4.2

【讨论】:

    【解决方案3】:

    在 swift 4.1 和 Xcode 10 中

    UITextFieldDelegate 添加到您的班级

    class YourViewController: UIViewController, UITextFieldDelegate
    

    然后在你的 viewDidLoad()

    中编写这段代码
    yourTF.delegate = self
    

    编写此文本字段委托函数

    //MARK - UITextField Delegates
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        //For numers
        if textField == yourTF {
            let allowedCharacters = CharacterSet(charactersIn:"0123456789")//Here change this characters based on your requirement
            let characterSet = CharacterSet(charactersIn: string)
            return allowedCharacters.isSuperset(of: characterSet)
        }
        return true
    }
    

    【讨论】:

      【解决方案4】:

      您可以使用UITextFieldDelegateshouldChangeCharactersInRange 方法将用户的输入限制为数字:

      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
      }
      

      为 Swift 3 更新:

       func textField(_ textField: UITextField, 
          shouldChangeCharactersIn range: NSRange, 
          replacementString string: String) -> Bool {
      
          // Create an `NSCharacterSet` set which includes everything *but* the digits
          let inverseSet = NSCharacterSet(charactersIn:"0123456789").inverted
      
          // 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.components(separatedBy: inverseSet)
      
          // Rejoin these components
          let filtered = components.joined(separator: "")  // 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  
      }
      

      【讨论】:

      • join("", components) 在 Swift 2.0 中中断,改为使用 components.joinWithSeparator("")
      • 漂亮的代码。这是一个如何编写自记录代码的模型。并且 dat 是唯一的代码。
      • let components = string.components(separatedBy: inverseSet) // 重新加入这些组件 let filters = components.joined(separator: "") for Swift 3
      • 以及如何处理这些函数?
      • 为什么你没有提到UITextFieldDelegate??
      【解决方案5】:

      iOS 没有提供这样的功能,您可以将文本字段指定为仅接受数字字符。唯一的方法是 UITextFieldDelegate 方法之一,如下所示,

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

      您需要实现以下方法并通过以下正则表达式截取输入的字符

      "^([0-9]+)?(\\.([0-9]{1,2})?)?$"
      

      [NSCharacterSet decimalDigitCharacterSet]
      

      可以判断输入的字符是否为数字,如果匹配正则表达式或字符集则返回YES,否则返回NO

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-10-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-04-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多