gpt4 book ai didi

objective-c - 如何使用 NSTextview 实现撤销

转载 作者:太空狗 更新时间:2023-10-30 03:41:30 24 4
gpt4 key购买 nike

我想在替换 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com