代码之家  ›  专栏  ›  技术社区  ›  d11wtq Vadim Baryshev

Cocoa(雪豹)NSTextView的textStorage-setAttributes:range:删除字符!

  •  2
  • d11wtq Vadim Baryshev  · 技术社区  · 14 年前

    我不知道我做错了什么。我有一个NSTextView,并注册为其textStorage属性的委托。当我收到 -textStorageDidProcessEditing:notification: 我试图将属性应用于文本中的字符范围。它当然对角色有“作用”,但不是我所期望的。。。他们消失了!

    一个经过大量提炼的代码示例。这应确保文本字段中的第二个字符始终为红色:

    -(void)textStorageDidProcessEditing:(NSNotification *)notification {
      NSTextStorage *textStorage = [textView textStorage];
      if ([[textStorage string] length] > 1) {
        NSColor *color = [NSColor redColor];
        NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:color, NSForegroundColorAttributeName, nil];
        [textStorage setAttributes:attributes range:NSMakeRange(1, 1)];
      }
    }
    

    如果我开始按backspace键,我必须按backspace键7次,好像“b”实际上在那里,但只是没有被绘制出来(光标在删除“b”时暂停,然后在下一个backspace键上按预期删除“a”)。

    如果我使用相同的 -setAttributes:range: 方法 画出了这幅图,然后它就如我所期望的那样。

    有线索吗?它似乎是一个相当正常的使用 NSTextStorageDelegate

    我试过打电话 -setNeedsDisplay 在文本字段中无效。

    2 回复  |  直到 14 年前
        1
  •  4
  •   d11wtq Vadim Baryshev    14 年前

    明白了。使用NSTextStorage的 -addAttribute:value:range 作品。我仍然不完全明白为什么,但至少我可以克服它,继续前进。

    -(void)textStorageDidProcessEditing:(NSNotification *)notification {
      // ... SNIP ...
      [textStorage addAttribute:NSForegroundColorAttributeName
                          value:[NSColor redColor]
                          range:NSMakeRange(1, 1)];
    }
    

    使代码也不那么混乱。

        2
  •  0
  •   Ecir Hana    10 年前

    我不知道这么多年后这对你有多重要,但我想原因是你 设置 NSFontAttributeName ,有效地将其从文本视图中移除。

    所以我认为这应该管用:

    -(void)textStorageDidProcessEditing:(NSNotification *)notification {
      NSTextStorage *textStorage = [textView textStorage];
      if ([[textStorage string] length] > 1) {
        NSColor *color = [NSColor redColor];
        NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys:color, NSForegroundColorAttributeName, [NSFont ...whatever...], NSFontAttributeName, nil];
        [textStorage setAttributes:attributes range:NSMakeRange(1, 1)];
      }
    }