简体   繁体   English

将 UITextField 输入限制为 Swift 中的数字

[英]Limit UITextField input to numbers in Swift

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

You can use UITextFieldDelegate 's shouldChangeCharactersInRange method to limit the user's input to numbers:您可以使用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
}

Updated for Swift 3:为 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  
}

For anyone looking for a shorter answer, I've found this quite useful.对于寻找更简短答案的人来说,我发现非常有用。

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

Works in XCode 10.1, Swift 4.2适用于 XCode 10.1、Swift 4.2

1st you have to inherit the UITextViewDelegate class with you own class 1st 你必须用你自己的类继承 UITextViewDelegate 类

class ViewController: UIViewController, UITextViewDelegate {

2nd add an IBOutlet 2 添加一个 IBOutlet

@IBOutlet weak var firstName: UITextField!

3rd you have to assure this object is using第三,你必须确保这个对象正在使用

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

In swift 4.1 and Xcode 10在 swift 4.1 和 Xcode 10 中

Add UITextFieldDelegate to your classUITextFieldDelegate添加到您的班级

class YourViewController: UIViewController, UITextFieldDelegate

Then write this code in your viewDidLoad()然后在您的viewDidLoad() 中编写此代码

yourTF.delegate = self

Write this textfield delegate function编写此文本字段委托函数

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

Well the iOS provides no such functionality where you can specify textfield to accept only numeric characters.好吧,iOS 没有提供这样的功能,您可以指定文本字段仅接受数字字符。 The only way through would be, one of UITextFieldDelegate methods, which is as follows,唯一的方法是, UITextFieldDelegate方法之一,如下所示,

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

You need to implement the following method and intercept the entered character and either through the following regular expression您需要实现以下方法并拦截输入的字符,或者通过以下正则表达式

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

or或者

[NSCharacterSet decimalDigitCharacterSet]

you can find out whether the entered character is numeric and return YES if it matches the regular expression or character set else return NO .您可以找出输入的字符是否为数字,如果匹配正则表达式或字符集则返回YES否则返回NO

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM