2010-10-21 35 views
2

我不知道我在做什么错。我有一个NSTextView,并且已经注册为它的textStorage属性的委托。当我收到-textStorageDidProcessEditing:notification:我试图将属性应用于文本中的字符范围。它确实对人物有“某种”,但不是我所期望的......他们只是消失了!可可(Snow Leopard)NSTextView的textStorage -setAttributes:范围:删除字符!

沉重的代码示例。这应该确保在文本字段中的第二个字符始终是红色:

-(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”我得到“是”,那么当我打“B”看似什么也没有发生,那么当我点击“cdefg”打字发生正常,使最终结果“acdefg”...“b”丢失!

如果我开始退格退格,我必须按退格键7次,就好像“b”实际上存在,但没有画出来(光标停止,因为它删除了“b”,然后在下一个退格删除“a”如预期)。

如果我申请属性使用以前一样-setAttributes:range:方法的观点认为一些默认的绘制文本,然后它正是我期望的那样。

任何线索?这似乎是一个相当正常的使用NSTextStorageDelegate :)

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

+0

我偶然发现了别人的代码,他们通过文本视图的布局管理器这样做: '[[[TextView的textContainer]的layoutManager] setTemporaryAttributes:属性forCharacterRange:范围];' 这是现在的工作,直到我点击删除键,这会导致出界的异常。 – d11wtq 2010-10-21 22:58:38

+0

“如果我开始退格退格,我必须回退7次,就好像”b“实际存在,但是没有被绘制(光标停止,因为它会删除”b“,然后在下一个退格删除”a “如预期的那样)”。这种事情听起来像是当应用程序出现异常时发生的情况。在你的控制台中有类似的东西吗? – 2010-10-22 07:56:14

回答

4

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

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

使代码也不那么混乱。

0

我不知道如何相关,这是你经过这么多年,但我认为其原因是,你是设置属性与不包含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)]; 
    } 
}