【问题标题】:NSTextView: When to automatically insert characters (like auto-matching parenthesis)?NSTextView:何时自动插入字符(如自动匹配括号)?
【发布时间】:2012-06-04 15:18:24
【问题描述】:

我有一个NSTextView 并且我正在充当它的NSTextStorage 代表,所以我收到了textStorageWillProcessEditing:textStorageDidProcessEditing: 的回调,目前我正在使用did 回调更改文本的某些属性(为某些单词着色)。

我想做的是添加某些字符对的自动匹配。当用户输入( 时,我也想插入),但我不确定何时何地是合适的时间。

从文本存储委托协议中,它说will 方法可以让您更改要显示的文本.. 但我不太确定这意味着什么或我该怎么做。文本系统非常庞大且令人困惑。

我应该怎么做?

【问题讨论】:

    标签: macos cocoa nstextview nstextstorage


    【解决方案1】:

    在我的开源项目中,我将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)];
    }
    

    【讨论】:

      猜你喜欢
      • 2011-05-30
      • 2011-04-17
      • 1970-01-01
      • 2021-09-04
      • 2019-09-04
      • 2014-07-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多