在我的开源项目中,我进行了子类化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)];
}