Cocoa 可可(雪豹)NSTextView&x27;s textStorage-setAttributes:range:删除字符!

Cocoa 可可(雪豹)NSTextView&x27;s textStorage-setAttributes:range:删除字符!,cocoa,macos,nstextfield,appkit,Cocoa,Macos,Nstextfield,Appkit,我不确定我做错了什么。我有一个NSTextView,并注册为其textStorage属性的委托。当我收到-textStorageDidProcessEditing:notification:时,我试图将属性应用于文本中的字符范围。它当然对角色有“作用”,但不是我所期望的。。。他们就这样消失了 一个经过大量提炼的代码示例。这应确保文本字段中的第二个字符始终为红色: -(void)textStorageDidProcessEditing:(NSNotification *)notification

我不确定我做错了什么。我有一个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)];
  }
}
相反,当我输入序列“abcdefg”时,我得到了“a”,然后当我点击“b”时,似乎什么都没有发生,然后当我点击“cdefg”时,键入会正常发生,最终结果是“acdefg”。。。“b”不见了

如果我开始点击backspace,我必须点击backspace 7次,就好像“b”实际上在那里,但只是没有被画出来一样(光标暂停,因为它删除了“b”,然后在下一个backspace上按预期删除了“a”)

如果在绘制视图之前,我使用相同的
-setAttributes:range:
方法将属性应用于视图中的某些默认文本,那么它将完全按照我的预期执行

有什么线索吗?这似乎是一个相当正常的使用
NSTextStorageDelegate
:)


我试着在文本字段中调用
-setNeedsDisplay
,但没有成功。

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

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

使代码也不那么混乱。

我不确定这么多年后这对您有多重要,但我认为原因是您使用不包含
NSFontAttributeName
的字典设置属性,从而有效地将其从textview中删除

所以我认为这应该有效:

-(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)];
  }
}

我偶然发现了其他人的代码,他们通过文本视图的布局管理器做到了这一点:
[[textView textContainer]layoutManager]settemporationattributes:attributes for characterrange:range]
这项功能现在正在运行,直到我点击delete键,这导致了一个越界异常。“如果我开始点击backspace,我必须点击backspace 7次,就好像“b”实际上在那里,但只是没有被画出来(光标在删除“b”时暂停,然后在下一个backspace上按预期删除“a”)这类事情听起来像是应用程序出现异常时发生的事情。你的控制台里有类似的东西吗?