2010-10-21 38 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)]; 
    } 
}