2012-01-13 10 views
12

quiero implementar el Código por el cual puedo comenzar a insertar texto en cualquier posición del cursor en UITextView en iphone sdkcómo insertar texto en cualquier posición del cursor en uitextview?

¿Alguna idea? gracias de antemano ..

i arbitrados este enlace: iPhone SDK: How to create a UITextView that inserts text where you tap?

Pero no obtenerlo.

+0

Por favor, responda si alguien lo intentó antes. También estoy haciendo lo mismo pero no tengo éxito así que por favor ayuda. –

Respuesta

10

Esto es lo que uso con un teclado personalizado, parece que funciona bien, puede haber un enfoque más limpio, no estoy seguro.

NSRange range = myTextView.selectedRange; 
NSString * firstHalfString = [myTextView.text substringToIndex:range.location]; 
NSString * secondHalfString = [myTextView.text substringFromIndex: range.location]; 
myTextView.scrollEnabled = NO; // turn off scrolling 

NSString * insertingString = [NSString stringWithFormat:@"your string value here"]; 

myTextView.text = [NSString stringWithFormat: @"%@%@%@", 
       firstHalfString, 
       insertingString, 
       secondHalfString]; 
range.location += [insertingString length]; 
myTextView.selectedRange = range; 
myTextView.scrollEnabled = YES; // turn scrolling back on. 
+0

gracias es muy interesante lo he usado al eliminar la palabra donde el cursor se coloca en textview por mi teclado personalizado :) gracias de nuevo –

+0

Muy bien ... Gracias, Dan. –

18

La respuesta de Dan es cambiar manualmente el texto. No está funcionando bien con UndoManager de UITextView.

En realidad, es muy fácil insertar texto con la API del protocolo UITextInput, que es compatible con UITextView y UITextField.

[textView replaceRange:textView.selectedTextRange withText:insertingString]; 

Nota: Es selectedTextRange en el protocolo UITextInput, en lugar de selectedRange

+0

Gracias, funciona para mí. –

+0

¡Una buena Huang! – Rambatino

+0

¡Gran solución! – Will

4

La forma más sencilla (pero no va a reemplazar el texto seleccionado) es utilizar el insertText: método:

[textView insertText:@"some text you want to insert"]; 

UITextView corresponde a UITextInput que a su vez se ajusta a UIKeyInput.

1

Aquí está la respuesta de Glorfindel en Swift3. El texto que está insertando aquí se saca del portapapeles.

if let textRange = myTextView.selectedTextRange { 
    myTextView.replace(textRange, withText:UIPasteboard.general.string!) 
} 
Cuestiones relacionadas