【问题标题】:NSTextView not applying attributes to newly inserted textNSTextView 未将属性应用于新插入的文本
【发布时间】:2012-08-06 20:31:13
【问题描述】:

我有一个 NSTExtView 并正在使用 [theTextView.textStorage addAttribute: value: range:] 为某些文本范围设置属性

例如,我使用 [theTextView.textStorage addAttribute:NSBackgroundColorAttributeName value:[NSColor yellowColor] range:theSelectedRange]; 突出显示一个范围

问题是当我在该范围内手动键入新文本时,它没有突出显示。它将突出显示的范围分成 2 个范围,并在它们之间插入非突出显示的文本。有没有办法使新插入的文本也被突出显示?

【问题讨论】:

    标签: nstextview nsattributedstring


    【解决方案1】:

    当用户在您的 NSTextView 中键入新内容时,插入点将使用与当前字体相关联的任何属性(如果有)。这也称为文本视图的“typingAttributes”。在大多数情况下,用户将使用黑色和白色背景进行打字。

    现在,由于您正在突出显示(而不是进行选择),您需要做的是在光标的插入点处选取当前颜色。

    您可以通过以下方式获取属性:

    // I think... but am not 100% certain... the selected range
    // is the same as the insertion point.
    NSArray * selectedRanges = [theTextView selectedranges];
    if(selectedRanges && ([selectedRanges count] > 0))
    {
        NSValue * firstSelectionRangeValue = [selectedRanges objectAtIndex: 0];
        if(firstSelectionRangeValue)
        {
            NSRange firstCharacterOfSelectedRange = [firstSelectionRangeValue rangeValue];
    
            // now that we know where the insertion point is likely to be, let's get
            // the attributes of our text
            NSSDictionary * attributesDictionary = [theTextView.textStorage attributesAtIndex: firstCharacterOfSelectedRange.location effectiveRange: NULL];
    
            // set these attributes to what is being typed
            [theTextView setTypingAttributes: attributesDictionary];
    
            // DON'T FORGET to reset these attributes when your selection changes, otherwise
            // your highlighting will appear anywhere and everywhere the user types.
        }
    }
    

    我根本没有测试或尝试过这段代码,但这应该可以让你到达你需要的地方。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-06-30
      • 2011-07-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多