2

我不确定我做错了什么。我有一个 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”不见了!

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

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

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

我试过调用-setNeedsDisplay文本字段无济于事。

4

2 回答 2

4

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

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

也使代码不那么混乱。

于 2010-10-22T01:44:15.117 回答
0

经过这么多年,我不确定这对您有多重要,但我认为原因是您使用不包含的字典设置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)];
  }
}
于 2014-12-13T14:48:23.280 回答