我想在替换 NSTextView 中的部分文本后执行撤消操作。我正在用以下代码替换部分文本
- (void)omeAction
{
NSString *fullString = [self.textView string];
NSRange selectedRange = [self.textView selectedRange];
NSString *selectedString = [fullString substringWithRange:selectedRange];
NSString *stringToReplace = ...;
[[self.textView textStorage] beginEditing];
[[self.textView textStorage] replaceCharactersInRange:selectedRange withString:stringToReplace];
[[self.textView textStorage] endEditing];
}
在执行撤消时我无法真正撤消文本替换
最佳答案
来自 Cocoa Text Architecture Guide: Text Editing – Text Change Notifications and Delegate Messages :
In actually making changes to the text, you must ensure that the changes are properly performed and recorded by different parts of the text system. You do this by bracketing each batch of potential changes with shouldChangeTextInRange:replacementString: and didChangeText messages. These methods ensure that the appropriate delegate messages are sent and notifications posted. …
根据我的经验,这包括生成相关的撤消操作。
所以,你会这样做:
if ([self.textView shouldChangeTextInRange:selectedRange replacementString:stringToReplace])
{
[[self.textView textStorage] beginEditing];
[[self.textView textStorage] replaceCharactersInRange:selectedRange withString:stringToReplace];
[[self.textView textStorage] endEditing];
[self.textView didChangeText];
}
关于objective-c - 如何使用 NSTextview 实现撤销,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25590912/