gpt4 book ai didi

objective-c - NSTextView replaceCharactersInRange :withString: counterpart to shouldChangeTextInRanges:replacementStrings:

转载 作者:搜寻专家 更新时间:2023-10-30 19:42:54 25 4
gpt4 key购买 nike

我的一个项目中有一个相当复杂的 NSTextView 子类。我目前正在努力让查找/替换与内联查找栏(例如 Safari、Xcode)一起工作,并希望正确支持替换操作的撤消/重做。

我希望“全部替换”命令支持将撤消作为单个命令(即,如果要在 TextView 中进行 8 次替换,它也应该一次撤消这 8 次替换)。

我想知道是否有 shouldChangeTextInRanges:replaceStrings: 的对应项,我可以在检查完成替换后调用它。我预计会有 replaceCharactersInRanges:withStrings: 或类似的东西,但似乎没有。

目前我能想到的唯一方法是先调用 shouldChangeTextInRanges:replaceStrings:,然后调用 replaceCharactersInRange:withString: TextView 的整个范围和新字符串(进行了替换)作为第二个参数。

这似乎是不必要的,如果不需要的话,我真的不想替换整个字符串。有什么想法吗?

最佳答案

经过一番修改后,我想我已经弄明白了。乔希,我用你的建议开始了。我不确定你是编辑了你的建议还是只是删除了它,但它已经消失了所以我不能在我的回答中引用它。

无论如何,您必须在每次调用 replaceCharactersInRange:withString: 后移动要替换的范围,否则会因为范围不匹配而发生不好的事情。这是我最终得到的结果:

// array of NSValue objects storing an NSRange
NSArray *replaceRanges = [self replaceRanges];
NSString *replaceString = [self replaceString];
// array of NSString objects you are going to use for the replace operation, just replaceString repeated [replaceRanges count] times
NSArray *replaceStrings = [self replaceStrings];
NSTextView *textView = [self textView];
// the amount we have to shift subequent replace ranges after each call to replaceCharactersInRange:withString:
NSInteger locationShift = 0;

// check to makes sure the replace can occur
if ([textView shouldChangeTextInRanges:replaceRanges replacementStrings:replaceStrings]) {
// we want to treat all these replacements as a single replacement for undo purposes
[[textView textStorage] beginEditing];

for (NSValue *rangeValue in replaceRanges) {
NSRange range = [rangeValue rangeValue];

// replace the range shifted by locationShift with our replaceString
[[textView textStorage] replaceCharactersInRange:NSMakeRange(range.location + locationShift, range.length) withString:replaceString];

// update the shift amount, which is the difference between our replaced string length and the original match length
locationShift += [replaceString length] - range.length;
}
// end the grouping operation
[[textView textStorage] endEditing];
}

这很好用并且支持预期的撤消,撤消此操作会立即撤消所有替换。

无论如何,感谢 Josh,因为他的回答让我指明了正确的方向。

关于objective-c - NSTextView replaceCharactersInRange :withString: counterpart to shouldChangeTextInRanges:replacementStrings:,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5572519/

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