delegate iphone iphone-sdk-3.0 uitextfield textselection

iphone - delegate - textfield ios



¿Puedo seleccionar un bloque de texto específico en un UITextField? (6)

Tengo un UITextField en mi aplicación de iPhone. Sé cómo hacer que el campo de texto seleccione todo su texto, pero ¿cómo se puede cambiar la selección? Supongamos que quería seleccionar los últimos 5 caracteres, o un rango específico de caracteres, ¿es posible? si no, ¿puedo mover las líneas que marcan el comienzo y el final de la selección, como si el usuario las estuviera arrastrando?


Rápido

Seleccione los últimos 5 caracteres:

if let newPosition = textField.positionFromPosition(textField.endOfDocument, inDirection: UITextLayoutDirection.Left, offset: 5) { textField.selectedTextRange = textField.textRangeFromPosition(newPosition, toPosition: textField.endOfDocument) }

Seleccione un rango arbitrario:

// Range: 3 to 7 let startPosition = textField.positionFromPosition(textField.beginningOfDocument, inDirection: UITextLayoutDirection.Right, offset: 3) let endPosition = textField.positionFromPosition(textField.beginningOfDocument, inDirection: UITextLayoutDirection.Right, offset: 7) if startPosition != nil && endPosition != nil { textField.selectedTextRange = textField.textRangeFromPosition(startPosition!, toPosition: endPosition!) }

Mi respuesta completa está here .


Con UITextField, no puedes. Pero si ve los encabezados, ha seleccionado _selectedRange y otros que podrían usarse si agrega algunas categorías;)


Actualización para iOS5 y superior:

Ahora UITextField y UITextView cumplen con el protocolo UITextInput por lo que es posible :)

Seleccionar los últimos 5 caracteres antes del símbolo de intercalación sería así:

// 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:-5]; // Construct a new range using the object that adopts the UITextInput, our textfield UITextRange *newRange = [textField textRangeFromPosition:newPosition toPosition:selectedRange.start]; // Set new range [textField setSelectedTextRange:newRange];


Estos dos funcionan para mí:

[UITextField selectAll:self];

y:

UITextField.selectedRange = NSMakeRange(0, 5);

pero solo si el campo de texto es el primer respondedor. (En otras palabras, solo si se muestra el teclado.) Por lo tanto, debe preceder a cualquiera de los métodos de selección con esto:

[UITextField becomeFirstResponder];

si quieres que el texto aparezca seleccionado.


Para seleccionar el nombre de un archivo sin la extensión de archivo, use esto:

-(void) tableViewCellDidBeginEditing:(UITableViewTextFieldCell*) cell { NSInteger fileNameLengthWithoutExt = [self.filename length] - [[self.filename pathExtension] length]; UITextField* textField = cell.textField; UITextPosition* start = [textField beginningOfDocument]; UITextPosition* end = [textField positionFromPosition:start offset: fileNameLengthWithoutExt - 1]; // the -1 is for the dot separting file name and extension UITextRange* range = [textField textRangeFromPosition:start toPosition:end]; [textField setSelectedTextRange:range]; }


Para seleccionar un rango específico de caracteres, puedes hacer algo como esto en iOS 5+

int start = 2; int end = 5; UITextPosition *startPosition = [self positionFromPosition:self.beginningOfDocument offset:start]; UITextPosition *endPosition = [self positionFromPosition:self.beginningOfDocument offset:end]; UITextRange *selection = [self textRangeFromPosition:startPosition toPosition:endPosition]; self.selectedTextRange = selection;

Como UITextField y otros elementos de UIKit tienen sus propias subclases privadas de UITextPosition y UITextRange no puede crear valores nuevos directamente, pero puede usar el campo de texto para crearlos para usted a partir de una referencia al principio o al final del texto y un entero compensar.

También puede hacer lo contrario para obtener representaciones enteras de los puntos de inicio y fin de la selección actual:

int start = [self offsetFromPosition:self.beginningOfDocument toPosition:self.selectedTextRange.start]; int end = [self offsetFromPosition:self.beginningOfDocument toPosition:self.selectedTextRange.end];

Aquí hay una categoría que agrega métodos para manejar selecciones usando NSRange s. https://gist.github.com/4463233


Solo una pequeña adición a la respuesta aceptada. En iOS 5, la siguiente línea bloquea mi aplicación cuando la longitud del texto de UITextView es 0 (no tiene texto):

[self textRangeFromPosition:startPosition toPosition:endPosition];

Una pequeña solución es agregar una verificación de length == 0 como:

if (textField.text && textField.text.length > 0) { // 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:-5]; // Construct a new range using the object that adopts the UITextInput, our textfield UITextRange *newRange = [textField textRangeFromPosition:newPosition toPosition:selectedRange.start]; // Set new range [textField setSelectedTextRange:newRange]; }