我有一个 NSTextView
并且我充当它的 NSTextStorage
委托(delegate),因此我收到了 textStorageWillProcessEditing:
的回调并且textStorageDidProcessEditing:
,目前我正在使用 did
回调来更改文本上的某些属性(为某些单词着色)。
我想做的是添加某些字符对的自动匹配。当用户输入 (
时,我也想插入 )
但我不确定何时何地执行此操作的适当时间。
根据文本存储委托(delegate)协议(protocol),它表示 will
方法可以让您更改要显示的文本。但我不太确定这意味着什么或如何做到这一点。文本系统确实很大而且令人困惑。
我应该怎么做?
最佳答案
在我的开源项目中,我对 NSTextView 进行了子类化并覆盖了 insertText:
来处理匹配字符的插入。您可以检查 insertText:
的参数,看看它是否是您想要执行的操作,调用 super 执行正常的文本插入,然后再次调用 insertText:
如果需要,适当的匹配字符串。
类似这样的事情:
- (void)insertText:(id)insertString {
[super insertText:insertString];
// if the insert string isn't one character in length, it cannot be a brace character
if ([insertString length] != 1)
return;
unichar firstCharacter = [insertString characterAtIndex:0];
switch (firstCharacter) {
case '(':
[super insertString:@")"];
break;
case '[':
[super insertString:@"]"];
break;
case '{':
[super insertString:@"}"];
break;
default:
return;
}
// adjust the selected range since we inserted an extra character
[self setSelectedRange:NSMakeRange(self.selectedRange.location - 1, 0)];
}
关于macos - NSTextView:何时自动插入字符(如自动匹配括号)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10883738/