nac*_*o4d 10 iphone objective-c uitextview nsundomanager ios
我希望能够以编程方式替换UITextView中的某些文本,因此我将此方法编写为UITextView类别:
- (void) replaceCharactersInRange:(NSRange)range withString:(NSString *)newText{
self.scrollEnabled = NO;
NSMutableString *textStorage = [self.text mutableCopy];
[textStorage replaceCharactersInRange:range withString:newText];
//replace text but undo manager is not working well
[[self.undoManager prepareWithInvocationTarget:self] replaceCharactersInRange:NSMakeRange(range.location, newText.length)
withString:[textStorage substringWithRange:range]];
NSLog(@"before replacing: canUndo:%d", [self.undoManager canUndo]); //prints YES
self.text = textStorage;
NSLog(@"after replacing: canUndo:%d", [self.undoManager canUndo]); //prints NO
if (![self.undoManager isUndoing])[self.undoManager setActionName:@"replace characters"];
[textStorage release];
//new range:
range.location = range.location + newText.length;
range.length = 0;
self.selectedRange = range;
self.scrollEnabled = YES;
}
Run Code Online (Sandbox Code Playgroud)
它工作但NSUndoManager在self.text=textStorage
我找到一个私有API 之后就停止工作(它似乎被重置):-insertText:(NSString *)
可以完成这项工作,但是谁知道如果我使用它,Apple是否会批准我的应用程序.有没有办法在UITextView中使用NSUndoManager支持替换文本?或许我在这里遗失了什么?
实际上没有任何黑客或自定义类别的理由来完成此任务.您可以使用内置的UITextInput协议方法replaceRange:withText:
.要插入文本,您只需执行以下操作:
[textView replaceRange:textView.selectedTextRange withText:replacementText];
Run Code Online (Sandbox Code Playgroud)
这适用于iOS 5.0.撤消自动工作,没有奇怪的滚动问题.
在偶然发现这个问题并白发苍苍之后,我终于找到了令人满意的解决方案。它有点俗气,但它确实很有魅力。这个想法是使用 UITextView 提供的工作复制和粘贴支持!我想你可能感兴趣:
- (void)insertText:(NSString *)insert
{
UIPasteboard *pboard = [UIPasteboard generalPasteboard];
// Clear the current pasteboard
NSArray *oldItems = [pboard.items copy];
pboard.items = nil;
// Set the new content to copy
pboard.string = insert;
// Paste
[self paste: nil];
// Restore pasteboard
pboard.items = oldItems;
[oldItems release];
}
Run Code Online (Sandbox Code Playgroud)
编辑:当然,您可以自定义此代码以在文本视图中的任何位置插入文本。selectedRange
只需在调用之前设置即可paste
。
归档时间: |
|
查看次数: |
3205 次 |
最近记录: |