使用UITextView(iOS / iPHone)撤消/重做 [英] Undo/redo with a UITextView (iOS/iPHone)
问题描述
我有一个视图,其中UITextView始终具有焦点。我想要做的是扩展内置的撤消/重做行为,以便在我以编程方式设置文本时支持撤消/重做(例如,当我清除它时,通过将其设置为@)。
I have a view where a UITextView always has focus. What I want to do is extend the built-in undo/redo behavior to support undo/redo for when I programmatically set the text (e.g., for when I clear it, by setting it to @"").
由于只有firstResponder获取了undo / redo事件,我以为我只是使用UITextView的undoManager属性来创建我的调用。例如,
Since only the firstResponder gets undo/redo events, I thought I'd simply use the UITextView's undoManager property to create my invocations. e.g.,
// Before clearing the text...
[[self.myTextView.undoManager prepareWithInvocationTarget:self] undoClear:self.myTextView.text];
[self.myTextView.undoManager setActionName:@"Clear"];
// ...
-(void)undoClear:(NSString *)textToRestore
{
self.myTextView.text = textToRestore;
if ([self.myTextView.undoManager isUndoing])
{
// Prepare the redo.
[[self.myTextView.undoManager prepareWithInvocationTarget:self] undoClear:@""];
}
}
不幸的是,这不起作用。它:
Unfortunately, this is not working. It:
- 在撤销堆栈中引入一个空项目(撤消)
- 撤消清除在该项目后添加(如果我点击撤消,我看到撤消清除)
- 撤消清除和重做清除工作,然后,我看到撤消清除再次,它不起作用。
任何想法?我接近这个错误了吗?
Any ideas? Am I approaching this wrong?
更新:好像我已经找到了空的撤销项目问题:它发生在我设置时之后的UITextView 的文本我调用了prepareWithInvocationTarget。如果我之前打电话,它就不会发生。有趣的是,如果我不调用prepareWithInvocationTarget(即,通常,当我设置UITextView的文本时),空项目不会被推到撤消堆栈上。
Update: It seems like I've figured out the empty undo item issue: it happens when I set the text of the UITextView after I've called prepareWithInvocationTarget. If I call it before, it doesn't happen. Funny thing is, the empty item isn't pushed onto the undo stack if I don't call prepareWithInvocationTarget (i.e., normally, when I set the text of a UITextView).
推荐答案
好的,想通了:
#1的问题与原始帖子的更新中所述相同。
The issue with #1 is as outlined in the update to my original post.
问题#2和#3只是我错误地使用NSUndoManager。我的最终unClear方法(在undos上调用如下:
Issues #2 and #3 were just me using the NSUndoManager incorrectly. My final unClear method (which gets called on undos is as follows:
-(void)undoClear:(NSString *)textToRestore
{
NSString *textBackup = [self.myTextView.text copy];
self.myTextView.text = textToRestore;
if ([self.myTextView.undoManager isUndoing])
{
// Prepare the redo.
[[self.myTextView.undoManager prepareWithInvocationTarget:self] undoClear:@""];
}
else if ([self.myTextView.undoManager isRedoing])
{
[[self.myTextView.undoManager prepareWithInvocationTarget:self] undoClear:textBackup];
}
[textBackup release];
}
它现在正常运作。
这篇关于使用UITextView(iOS / iPHone)撤消/重做的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!