2012-06-22 9 views
24

alguien me puede ayudar con esto: tengo que implementar UITextField para el número de entrada. Este número siempre debe estar en formato decimal con 4 lugares, p. 12.3456 o 12.3400. Así que creé NSNumberFormatter que me ayuda con las posiciones decimales.cómo mover el cursor en UITextField después de establecer su valor

me he fijado en el valor UITextField método

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string . I entrada de proceso, use formateador y finalmente llame al [textField setText: myFormattedValue];

Esto funciona bien pero esta llamada también mueve el cursor al final de mi campo. Eso no es deseado P.ej. Tengo 12.3400 en mi campo y el cursor está ubicado al principio y el usuario escribe el número 1. El valor del resultado es 112.3400 pero el cursor se mueve al final. Quiero terminar con el cursor cuando el usuario espera (justo después del número 1 agregado recientemente). Hay algunos temas sobre cómo colocar el cursor en TextView, pero esto es UITextField. También intenté capturar selectedTextRange del campo, que guarda la posición del cursor correctamente pero después de la llamada al método setText, esto cambia automáticamente y se pierde el origen UITextRange (cambiado a actual). espero que mi explicación sea clara.

Por favor, ayúdenme con esto. muchas gracias.

EDIT: Finalmente, decidí cambiar la funcionalidad para cambiar el formato después de la edición completa y funciona lo suficientemente bien. Lo he hecho agregando un selector forControlEvents:UIControlEventEditingDidEnd.

+0

Cuando se lee la 'selectedTextRange', puede que no copiarla como una propiedad de la clase que actúa como el' UITextFieldDelegate' y luego re-set después de 'setText:'? –

+1

Phillip, eso no funciona.Después de establecer el texto con setText, el UITextRange que recopiló antes de configurar el texto se restablece a nulo, por lo que no puede volver a aplicarlo al UITextField finalizado. – JasonD

Respuesta

2

implementar el código descrito en esta respuesta: Moving the cursor to the beginning of UITextField

NSRange beginningRange = NSMakeRange(0, 0); 
NSRange currentRange = [textField selectedRange]; 
if(!NSEqualRanges(beginningRange, currentRange)) 
{ 
    [textField setSelectedRange:beginningRange]; 
} 

EDIT: De this answer, parece que sólo puede utilizar este código con el UITextField si está usando iOS 5 o superior. De lo contrario, debe usar una UITextView en su lugar.

38

Después de cambiar la propiedad UITextField.text, las referencias anteriores a UITextPosition o UITextRange objetos que se asociaron con el texto anterior se establecerán en nil después de establecer la propiedad del texto. Debe almacenar cuál será el desplazamiento de texto después de la manipulación ANTES de establecer la propiedad del texto.

Esto funcionó para mí (nota, usted tiene que probar si es cursorOffset < textField.text.length si se quita los caracteres de t en el ejemplo a continuación):

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

{ 
    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]; 

    // this will be the new cursor location after insert/paste/typing 
    NSInteger cursorOffset = [textField offsetFromPosition:beginning toPosition:start] + string.length; 

    // now apply the text changes that were typed or pasted in to the text field 
    [textField replaceRange:textRange withText:string]; 

    // now go modify the text in interesting ways doing our post processing of what was typed... 
    NSMutableString *t = [textField.text mutableCopy]; 
    t = [t upperCaseString]; 
    // ... etc 

    // now update the text field and reposition the cursor afterwards 
    textField.text = t; 
    UITextPosition *newCursorPosition = [textField positionFromPosition:textField.beginningOfDocument offset:cursorOffset]; 
    UITextRange *newSelectedRange = [textField textRangeFromPosition:newCursorPosition toPosition:newCursorPosition]; 
    [textField setSelectedTextRange:newSelectedRange]; 

    return NO; 
} 
+2

Funcionó muy bien para mí. Gracias, JasonD! –

+2

Funciona a la perfección. ¡¡¡Gracias!!! – RohinNZ

+0

tnx mucho, he agregado la versión rápida a continuación para los perezosos :) – ergunkocak

3

Y aquí es la rápida versión:

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { 
    let beginning = textField.beginningOfDocument 
    let start = textField.positionFromPosition(beginning, offset:range.location) 
    let end = textField.positionFromPosition(start!, offset:range.length) 
    let textRange = textField.textRangeFromPosition(start!, toPosition:end!) 
    let cursorOffset = textField.offsetFromPosition(beginning, toPosition:start!) + string.characters.count 

// just used same text, use whatever you want :) 
    textField.text = (textField.text! as NSString).stringByReplacingCharactersInRange(range, withString: string) 

    let newCursorPosition = textField.positionFromPosition(textField.beginningOfDocument, offset:cursorOffset) 
    let newSelectedRange = textField.textRangeFromPosition(newCursorPosition!, toPosition:newCursorPosition!) 
    textField.selectedTextRange = newSelectedRange 

    return false 
} 
2

He aquí una rápida versión 3

extension UITextField { 
    func setCursor(position: Int) { 
     let position = self.position(from: beginningOfDocument, offset: position)! 
     selectedTextRange = textRange(from: position, to: position) 
    } 
} 
0

Lo que en realidad w orked para mí era muy simple acaba de utilizar asíncrono, despacho principal:

DispatchQueue.main.async(execute: { 
    textField.selectedTextRange = textField.textRange(from: start, to: end) 
}) 
Cuestiones relacionadas