UITextField debería aceptar valores solo de número

Tengo UITexfields, quiero que solo acepte el número de otras alertas de muestra que ingresan un valor numérico. Quiero que motionSicknessTextFiled solo acepte el número

NSString*dogswithMotionSickness=motionSicknessTextField.text; NSString*valueOne=cereniaTextField.text; NSString*valueTwo=prescriptionTextField.text; NSString*valueThree=otherMeansTextField.text; NSString*valueFour=overtheCounterTextField.text; 

En cualquier UITextField del que obtienes estos valores, puedes especificar el tipo de keyboard que deseas que aparezca cuando alguien toca dentro del campo de text.

EG un keyboard numérico solo.

Me gusta esta captura de pantalla:

solo aparecerá el teclado numérico

Esto se configura fácilmente cuando se trabaja con el XIB y el Interface Builder integrado en Xcode, pero si quiere comprender esto de manera programática, consulte la página de reference del protocolo UITextInputTraits de Apple , específicamente la información de propiedad keyboardType .

Para filtrar las puntuaciones, establezca el delegado del campo de text y configure el método shouldChangeCharactersInRange:

 - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {  NSCharacterSet *numbersOnly = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"]; NSCharacterSet *characterSetFromTextField = [NSCharacterSet characterSetWithCharactersInString:textField.text];  BOOL stringIsValid = [numbersOnly isSupersetOfSet:characterSetFromTextField];  return stringIsValid; } 

C objective

 - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { if (!string.length) return YES; if (textField == self.tmpTextField) { NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string]; NSString *expression = @"^([0-9]+)?(\\.([0-9]{1,2})?)?$"; NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:expression options:NSRegularExpressionCaseInsensitive error:nil]; NSUInteger numberOfMatches = [regex numberOfMatchesInString:newString options:0 range:NSMakeRange(0, [newString length])]; if (numberOfMatches == 0) return NO; } return YES; } 

Swift 3.0

 func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { if !string.characters.count { return true } do { if textField == self.tmpTextField { var newString = textField.text.replacingCharacters(inRange: range, with: string) var expression = "^([0-9]+)?(\\.([0-9]{1,2})?)?$" var regex = try NSRegularExpression(pattern: expression, options: NSRegularExpressionCaseInsensitive) var numberOfMatches = regex.numberOfMatches(inString: newString, options: [], range: NSRange(location: 0, length: newString.characters.count)) if numberOfMatches == 0 { return false } } } catch let error { } return true } 
 [textField setKeyboardType:UIKeyboardTypeNumberPad]; 

He implementado el fragment que tiene las características para textField:

  1. Compruebe los caracteres máximos permitidos .
  2. Verifique el número decimal válido .
  3. Verifique solo los numbers numéricos .

El código es el método de delegado UITextField . Antes de usar este fragment, debe tener estas properties:

  1. self.maxCharacters
  2. self.numeric // Solo caracteres int .
  3. self.decimalNumeric // Solo numbers y ".", "," (para locales específicos, como ruso).

Código:

 - (BOOL)textField:(UITextField *) textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { if(self.numeric || self.decimalNumeric) { NSString *fulltext = [textField.text stringByAppendingString:string]; NSString *charactersSetString = @"0123456789"; // For decimal keyboard, allow "dot" and "comma" characters. if(self.decimalNumeric) { charactersSetString = [charactersSetString stringByAppendingString:@".,"]; } NSCharacterSet *numbersOnly = [NSCharacterSet characterSetWithCharactersInString:charactersSetString]; NSCharacterSet *characterSetFromTextField = [NSCharacterSet characterSetWithCharactersInString:fulltext]; // If typed character is out of Set, ignore it. BOOL stringIsValid = [numbersOnly isSupersetOfSet:characterSetFromTextField]; if(!stringIsValid) { return NO; } if(self.decimalNumeric) { NSString *currentText = [textField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]; // Change the "," (appears in other locale keyboards, such as russian) key ot "." currentText = [currentText stringByReplacingOccurrencesOfString:@"," withString:@"."]; // Check the statements of decimal value. if([fulltext isEqualToString:@"."]) { textField.text = @"0."; return NO; } if([fulltext rangeOfString:@".."].location != NSNotFound) { textField.text = [fulltext stringByReplacingOccurrencesOfString:@".." withString:@"."]; return NO; } // If second dot is typed, ignore it. NSArray *dots = [fulltext componentsSeparatedByString:@"."]; if(dots.count > 2) { textField.text = currentText; return NO; } // If first character is zero and second character is > 0, replace first with second. 05 => 5; if(fulltext.length == 2) { if([[fulltext substringToIndex:1] isEqualToString:@"0"] && ![fulltext isEqualToString:@"0."]) { textField.text = [fulltext substringWithRange:NSMakeRange(1, 1)]; return NO; } } } } // Check the max characters typed. NSUInteger oldLength = [textField.text length]; NSUInteger replacementLength = [string length]; NSUInteger rangeLength = range.length; NSUInteger newLength = oldLength - rangeLength + replacementLength; BOOL returnKey = [string rangeOfString: @"\n"].location != NSNotFound; return newLength <= _maxCharacters || returnKey; } 

Manifestación:

introduzca la descripción de la imagen aquí

Modificado la respuesta de Michael Dautermann:

 - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { if(string.length > 0) { NSCharacterSet *numbersOnly = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"]; NSCharacterSet *characterSetFromTextField = [NSCharacterSet characterSetWithCharactersInString:string]; BOOL stringIsValid = [numbersOnly isSupersetOfSet:characterSetFromTextField]; return stringIsValid; } return YES; } 

esta es la function que busca la cadena que contiene solo el valor numérico

 +(BOOL) checkforNumeric:(NSString*) str { NSString *strMatchstring=@"\\b([0-9%_.+\\-]+)\\b"; NSPnetworkingicate *textpnetworkingicate=[NSPnetworkingicate pnetworkingicateWithFormat:@"SELF MATCHES %@", strMatchstring]; if(![textpnetworkingicate evaluateWithObject:str]) { //////NSLog(@"Invalid email address found"); UIAlertView *objAlert = [[UIAlertView alloc] initWithTitle:APP_NAME message:@"please enter valid text." delegate:nil cancelButtonTitle:nil otherButtonTitles:@"Close",nil]; [objAlert show]; [objAlert release]; return FALSE; } return TRUE; } 

verifíquelo en el button enviar.

Aquí está la solución Swift:

En viewDidLoad establece el delegado:

 _yourTextField.delegate = self 
 let _acceptableCharacters = "0123456789." func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { if (string.characters.count == 0) { return true } if (textField == self._yourTextField) { let cs = NSCharacterSet(charactersInString: self._acceptableCharacters) let filtenetworking = string.componentsSeparatedByCharactersInSet(cs).filter { !$0.isEmpty } let str = filtenetworking.joinWithSeparator("") return (string != str) } return true } 

Acabo de modificar la respuesta de Michael e hice que sea un poco más fácil de implementar. Solo asegúrese de que el delegado de su UITextfield esté configurado en sí mismo.

 yourTxtField.delegate = self; 

Además, copie y pegue este código en su file principal.

 - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { if (textField == yourTxtField) { NSCharacterSet *numbersOnly = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"]; NSCharacterSet *characterSetFromTextField = [NSCharacterSet characterSetWithCharactersInString:string]; BOOL stringIsValid = [numbersOnly isSupersetOfSet:characterSetFromTextField]; return stringIsValid; }else { return YES; } } 

Si desea permitir el uso de la barra espaciadora, simplemente coloque un espacio en blanco al final de CharactersInString , así:

 @"0123456789" -> @"0123456789 " 

Adicionalmente:

Si desea restringir la longitud de la cadena simplemente reemplace la function if con los siguientes:

 if (textField == yourTxtField) { NSUInteger newLength = [textField.text length] + [string length] - range.length; NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:@"1234567890"] invertedSet]; NSString *filtenetworking = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""]; return (([string isEqualToString:filtenetworking])&&(newLength <= 10)); } 

En mi caso, el "10" al final representa el límite de caracteres.

¡Aclamaciones! 🙂

Rápido

 class ExampleVC: UIViewController { let numbers = "0123456789"; override func viewDidLoad() { super.viewDidLoad() let textfield = UITextField(frame: CGRectMake(20, 100, 300, 44)) //make some customization, if you want self.view.addSubview(textfield) textfield.delegate = self; } } extension ExampleVC: UITextFieldDelegate { func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { return string.characters.count > 0 ? numbers.contains(string) : true } } 

@HimanshuPadia respuesta arrojó un error en Swift 3, aquí está la respuesta de trabajo:

 func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { if string.characters.count == 0 { return true } do { if textField == self.numberTextField { let nString = textField.text as NSString? let newString = nString?.replacingCharacters(in: range, with: string) let expression = "^([0-9]+)?(\\.([0-9]{1,2})?)?$" let regex = try NSRegularExpression(pattern: expression, options: .caseInsensitive) let numberOfMatches = regex.numberOfMatches(in: newString! as String, options: [], range: NSRange(location: 0, length: (newString?.characters.count)!)) if numberOfMatches == 0 { return false } } } catch let error { } return true }