Limitar la input de UITextField a los numbers en Swift

¿Cómo puedo limitar la input de TextField del usuario a los numbers en Swift?

Puede usar shouldChangeCharactersInRange para limitar la input del usuario a los numbers:

 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 filtenetworking = components.joinWithSeparator("") // use join("", components) if you are using Swift 1.2 // If the original string is equal to the filtenetworking 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 == filtenetworking } 

Actualizado para 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 filtenetworking = components.joined(separator: "") // use join("", components) if you are using Swift 1.2 // If the original string is equal to the filtenetworking 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 == filtenetworking } 

Bueno, el iOS no ofrece esa funcionalidad en la que puede especificar el campo de text para aceptar solo caracteres numéricos. El único path sería, uno de los methods UITextFieldDelegate , que es el siguiente,

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

Debe implementar el siguiente método e interceptar el carácter ingresado y mediante la siguiente expresión regular

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

o

 [NSCharacterSet decimalDigitCharacterSet] 

puede averiguar si el carácter introducido es numérico y devolver si coincide con la expresión regular o el set de caracteres, si no, devuelva NO .