2012-01-13 115 views

回答

10

这是我用自定义键盘,似乎工作正常,可能有一个更清洁的方法,不知道。

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

thanx它是非常有趣的,我用它删除光标放在我的自定义键盘的文本中的词:) thanx再次 – 2013-01-28 06:42:07

+0

非常好...谢谢,丹。 – 2013-03-01 06:34:21

18

丹的答案是手动更改文本。 UITextView的UndoManager效果不佳。

实际上,使用UITextInput协议API(UITextView和UITextField支持)可以很容易地插入文本。

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

注:这是selectedTextRange在UITextInput协议,而不是的selectedRange

+0

谢谢你对我有用。 – 2014-07-04 14:33:36

+0

不错的一个黄! – Rambatino 2014-11-17 20:55:36

+0

伟大的解决方案! – Will 2015-04-22 07:08:23

4

最简单的方法(但它不会取代所选文本)是使用insertText:方法:

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

UITextView符合UITextInput,其本身符合UIKeyInput

1

这是Glorfindel在Swift3中的回答。它插入的文本从剪贴板中拉出。

if let textRange = myTextView.selectedTextRange { 
    myTextView.replace(textRange, withText:UIPasteboard.general.string!) 
} 
相关问题