ios uitextfield uitextrange uitextposition

ios - UITextPosition en UITextField



uitextrange (2)

¿Hay alguna manera para que pueda llegar a la posición del cursor actual de un UITextField a través del objeto UITextRange del campo de texto? ¿Es el UITextRange devuelto por UITextField incluso de algún uso? La interfaz pública para UITextPosition no tiene miembros visibles.


Estaba enfrentando el mismo problema anoche. Resulta que tiene que usar offsetFromPosition en el UITextField para obtener la posición relativa del "inicio" del rango seleccionado para calcular la posición.

p.ej

// Get the selected text range UITextRange *selectedRange = [self selectedTextRange]; //Calculate the existing position, relative to the beginning of the field int pos = [self offsetFromPosition:self.beginningOfDocument toPosition:selectedRange.start];

Terminé usando endOfDocument ya que era más fácil restaurar la posición del usuario después de cambiar el campo de texto. Escribí un blog publicando sobre eso aquí:

http://neofight.wordpress.com/2012/04/01/finding-the-cursor-position-in-a-uitextfield/


Utilicé una categoría en uitextfield e implementé setSelectedRange y selectedRange (al igual que los métodos implementados en la clase uitextview). Un ejemplo se encuentra en B2Cloud here , con su código a continuación:

@interface UITextField (Selection) - (NSRange) selectedRange; - (void) setSelectedRange:(NSRange) range; @end @implementation UITextField (Selection) - (NSRange) selectedRange { UITextPosition* beginning = self.beginningOfDocument; UITextRange* selectedRange = self.selectedTextRange; UITextPosition* selectionStart = selectedRange.start; UITextPosition* selectionEnd = selectedRange.end; const NSInteger location = [self offsetFromPosition:beginning toPosition:selectionStart]; const NSInteger length = [self offsetFromPosition:selectionStart toPosition:selectionEnd]; return NSMakeRange(location, length); } - (void) setSelectedRange:(NSRange) range { UITextPosition* beginning = self.beginningOfDocument; UITextPosition* startPosition = [self positionFromPosition:beginning offset:range.location]; UITextPosition* endPosition = [self positionFromPosition:beginning offset:range.location + range.length]; UITextRange* selectionRange = [self textRangeFromPosition:startPosition toPosition:endPosition]; [self setSelectedTextRange:selectionRange]; } @end