2012-03-19 20 views
15

¿Hay alguna forma de que pueda acceder a la posición actual de intercalación de UITextField a través del objeto UITextRange del campo de texto? ¿El UITextRange devuelto por UITextField es de cualquier utilidad? La interfaz pública para UITextPosition no tiene ningún miembro visible.UITextPosition en UITextField

Respuesta

20

Estaba enfrentando el mismo problema anoche. Resulta que debe usar offsetFromPosition en 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 el endOfDocument ya que era más fácil para restaurar la posición del usuario después de cambiar el campo de texto. Me escribió una entrada de blog en ese aquí:

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

+1

su punto de enlace a un sitio sospechoso de malware. Por favor, échale un vistazo –

12

que utiliza una categoría en UITextField e implementado 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 
+0

Gracias. Tu código me ayudó a descubrir cómo puedo usar 'UITextPosition' con' UITextView'. – derpoliuk