2012-01-13 110 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!) 
} 
相關問題