solo poner mayusculas mayuscula escribir dejar como activada iphone cocoa-touch uitextfield uppercase

poner - como escribir solo mayusculas en iphone



iPhone fuerza entrada de cuadro de texto a mayúsculas (11)

¿Cómo forzar la entrada de caracteres en un cuadro de texto en el iPhone a mayúsculas?


En lugar de probar si el personaje está en mayúscula o minúscula, solo asuma que está en minúscula. Mucho más simple

En el

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

método:

NSString *newString = [[textField.text stringByAppendingString:string] uppercaseString]; textField.text = newString; return NO;


Esta solución no es completamente satisfactoria.

Incluso con el tipo de autocapitalizationType establecido en UITextAutocapitalizationTypeAllCharacters , el usuario puede presionar los topes para liberar el bloqueo de mayúsculas. Y textField.text = [textField.text stringByReplacingCharactersInRange:range withString:[string uppercaseString]]; return NO; textField.text = [textField.text stringByReplacingCharactersInRange:range withString:[string uppercaseString]]; return NO; La solución no es tan buena: perdemos el punto de edición si el usuario edita la mitad del texto (después de textField.text = , el cursor de edición va al final de la cadena).

He hecho una combinación de las dos soluciones y esto es lo que propongo: establezca UITextAutocapitalizationTypeAllCharacters y agregue el siguiente código al delegado de UITextField .

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { // Check if the added string contains lowercase characters. // If so, those characters are replaced by uppercase characters. // But this has the effect of losing the editing point // (only when trying to edit with lowercase characters), // because the text of the UITextField is modified. // That is why we only replace the text when this is really needed. NSRange lowercaseCharRange; lowercaseCharRange = [string rangeOfCharacterFromSet:[NSCharacterSet lowercaseLetterCharacterSet]]; if (lowercaseCharRange.location != NSNotFound) { textField.text = [textField.text stringByReplacingCharactersInRange:range withString:[string uppercaseString]]; return NO; } return YES; }


Este es mi código, cuando tengo 6 textFields

Espero que entiendas el punto

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { if (textField==self.textField6) { self.textField6.text = [textField.text stringByReplacingCharactersInRange:range withString:[string uppercaseString]]; return NO; } return YES; }


La forma más simple sería implementar el método de edición modificado del campo de texto y establecer el valor de texto del campo de texto en la representación en mayúscula del texto ingresado.

- (IBAction)TextFieldEditingChanged:(id)sender { _yourTextField.text = [_yourTextField.text uppercaseString]; }


Me han inspirado las respuestas anteriores (gracias), pero todas tenían algunos defectos:

  • usar textField.autocapitalizationType no ayuda cuando también quiere minúsculas o incluso más control.
  • textField.text = "my String" establece el cursor al final del textField que es realmente molesto cuando se edita.

Así que este es mi código Swift que le da control total sobre los caracteres escritos (mayúsculas, minúsculas, ignorar ...) Y deja el cursor donde lo espera. El código ha sido probado para que funcione con más de un textField.

Edición: probado con iOS 8.3

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { // modify string as and if the user wants: // at this place you can also return false to ignore the replacement completely. var str = string if !Defaults.isUpperOrLower() { if Defaults.isAllLetterUpper() { str = string.uppercaseString } else { str = string.lowercaseString } } // updating textField.text sets the curser position to the end // so we store the cursor position before updating. let selRange = textField.selectedTextRange // Update textField as requested and modified. var txt = textField.text as NSString textField.text = txt.stringByReplacingCharactersInRange(range, withString: str) // recalculate and set the cursor position in the textField: // tested with // 1. typing a character // 2. backspace // 3. selecting a range + backspace // 4. selecting a range + typing a character if let selRange = selRange { var newPosition: UITextPosition? if range.length == 0 { // normal character newPosition = textField.positionFromPosition(selRange.end, inDirection: UITextLayoutDirection.Right, offset: count(string)) } else { // backspace newPosition = textField.positionFromPosition(selRange.end, inDirection: UITextLayoutDirection.Left, offset: range.length - count(string)) } textField.selectedTextRange = textField.textRangeFromPosition(newPosition, toPosition: newPosition) } // return false because we did everything manually return false }


Mientras que todas las otras respuestas realmente funcionan (hacen que la entrada sea mayúscula), todas tienen el problema de que la posición del cursor no se conserva (intente insertar un carácter en el medio del texto existente). Esto aparentemente ocurre en el setter de la propiedad de text de UITextField , y no he encontrado una manera de restaurarlo programáticamente (por ejemplo, restaurar el original selectedTextRange TextRange no funciona).

Sin embargo, la buena noticia es que hay una manera directa de reemplazar partes del texto de UITextField (o UITextView ), que no sufre este problema:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { // not so easy to get an UITextRange from an NSRange... // thanks to Nicolas Bachschmidt (see http://.com/questions/9126709/create-uitextrange-from-nsrange) UITextPosition *beginning = textField.beginningOfDocument; UITextPosition *start = [textField positionFromPosition:beginning offset:range.location]; UITextPosition *end = [textField positionFromPosition:start offset:range.length]; UITextRange *textRange = [textField textRangeFromPosition:start toPosition:end]; // replace the text in the range with the upper case version of the replacement string [textField replaceRange:textRange withText:[string uppercaseString]]; // don''t change the characters automatically return NO; }

Para obtener más información sobre estos métodos, consulte la documentación de UITextInput .


Para ingresar automáticamente mayúsculas en el campo de texto:

Caso 1: agregar el protocolo UITextDelegate e implementar el siguiente método

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { textField.text = [textField.text stringByReplacingCharactersInRange:range withString:[string capitalizedString]]; return NO; }

Caso 2: establezca el siguiente parámetro en el método ViewDidLoad () en su controlador de vista. Aunque en este caso el usuario puede desactivar el botón de mayúsculas en el teclado.

urTextFieldName.autocapitalizationType = UITextAutocapitalizationTypeAllCharacters;


Tal vez no he encontrado todas las fallas en este método, pero hasta ahora me funciona bien. Parece evitar los problemas con saltar la selección hasta el final si se baja por la ruta de devolver NO desde -textField: shouldChangeCharactersInRange: replacementString:. Dado que UITextField se ajusta a UIKeyInput, simplemente anule el método -insertText: para cambiar la cadena de entrada a mayúscula antes de llamar a super con la cadena en mayúscula:

- (void)insertText:(NSString *)text { NSString *uppercaseText = [text uppercaseString] [super insertText:uppercaseText] }

O si te has mudado a Swift:

override func insertText(text: String) { let uppercaseText = text.uppercaseString super.insertText(uppercaseText) }


Una de las cuestiones que tengo con algunas de las respuestas anteriores es que si intentas establecer textfield.text , perderás la posición del cursor. Entonces, si un usuario intenta editar el medio del texto, el cursor saltará hasta el final .

Aquí está mi solución Swift simple, todavía usando UITextFieldDelegate :

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { if textField == textFieldToUppercase { if string == "" { // User presses backspace textField.deleteBackward() } else { // User presses a key or pastes textField.insertText(string.uppercaseString) } // Do not let specified text range to be changed return false } return true }

Todavía tiene que manejar si un usuario presiona la tecla Retorno , Hecho , etc. en el teclado. Solo agrega:

if string == "/n" { // Do something when ''Done'' is pressed, like dismiss the keyboard textField.resignFirstResponder() return false }

... dentro de func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool .


return NO tendrá problemas con el botón Atrás;

beter usa esto

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{ if ([[string uppercaseString] isEqualToString:string]) { return YES; } NSString *newString = [[textField.text stringByAppendingString:string] uppercaseString]; textField.text = newString; return NO; }