将UITextFieldinput限制在Swift中的数字

我怎样才能限制用户的TextFieldinput到Swift中的数字?

您可以使用shouldChangeCharactersInRange将用户的input限制为数字:

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

那么iOS不提供这样的function,你可以指定文本字段只接受数字字符。 通过唯一的方法将是, UITextFieldDelegate方法之一,如下所示,

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

您需要实现以下方法并拦截input的字符,并通过以下正则expression式

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

要么

 [NSCharacterSet decimalDigitCharacterSet] 

你可以找出input的字符是否是数字,如果与正则expression式或字符集匹配则返回YES ,否则返回NO