2010-11-14 19 views

Respuesta

8

Estás luchando contra el sistema en este caso. UITextField no tiene propiedades públicas para establecer la posición del cursor (que en realidad se correlaciona con el comienzo de la selección actual). Si puede usar un UITextView en su lugar, los siguientes métodos de delegado forzarán al cursor al comienzo del texto. Solo tenga en cuenta que los usuarios no esperarán este comportamiento y que deben verificar sus motivos para querer hacerlo.

- (void)textViewDidBeginEditing:(UITextView *)textView { 
    shouldMoveCursor = YES; 
} 

- (void)textViewDidChangeSelection:(UITextView *)textView { 
    if(shouldMoveCursor) 
    { 
     NSRange beginningRange = NSMakeRange(0, 0); 
     NSRange currentRange = [textView selectedRange]; 
     if(!NSEqualRanges(beginningRange, currentRange)) 
      [textView setSelectedRange:beginningRange]; 
     shouldMoveCursor = NO; 
    } 
} 

Dónde shouldMoveCursor es una variable BOOL a mantener en su controlador.

+0

Hey warrenm, thaks amigo. Este código es simplemente genial. Felicitaciones a usted. – anshul

19

UITextField cumple con el protocolo UITextInput, que proporciona métodos que le permiten controlar el rango seleccionado. Esto funciona en mis pruebas:

-(void)textFieldDidBeginEditing:(UITextField *)textField { 
    textField.selectedTextRange = [textField 
     textRangeFromPosition:textField.beginningOfDocument 
     toPosition:textField.beginningOfDocument]; 
} 
+0

¡Esta solución funciona genial! Asegúrese de cumplir con el protocolo delegado UITextField. :) –

1

funciona para mí

// Get current selected range , this example assumes is an insertion point or empty selection 
UITextRange *selectedRange = [textField selectedTextRange]; 
// Calculate the new position, - for left and + for right 
UITextPosition *newPosition = [textField positionFromPosition:selectedRange.start offset:3]; 
// Construct a new range using the object that adopts the UITextInput, our textfield 
UITextRange *newRange = [textField textRangeFromPosition:newPosition toPosition:newPosition]; 
// Set new range 
[textField setSelectedTextRange:newRange]; 
Cuestiones relacionadas