2012-12-31 120 views
0

我想通過子類化NSNumberFormatter在Objective C中編寫自己的自定義格式化程序。具體而言,我想要做的是如果數字高於或低於特定值,則會使數字變爲紅色。 apple documentation表示目標C中的自定義NSFormatter

例如,如果您希望負面財務金額顯示爲紅色,您可以使用此方法返回帶有紅色文本屬性的字符串。在attributesStringForObjectValue:withDefaultAttributes中:通過調用stringForObjectValue獲取非屬性字符串:然後將適當的屬性應用於該字符串。

基於此意見,我採取了以下代碼

- (NSAttributedString*) attributedStringForObjectValue: (id)anObject withDefaultAttributes: (NSDictionary*)attr; 
{ 
    NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:[self stringForObjectValue:anObject]]; 

    if ([[attrString string] floatValue] < -20.0f) { 
     [attrString addAttribute:@"NSForegroundColorAttributeName" value:[NSColor redColor] range:NSMakeRange(0, 10)]; 
     return attrString; 
    } else return attrString; 
} 

但是當我測試這一切確實是凍結我的應用程序。任何意見,將不勝感激。謝謝。

+0

您的號碼總是有10位數字嗎?你應該使用'NSMakeRange(0,attrString.length)'而不是'NSMakeRange(0,10)'。 – omz

+0

未來,如果你得到了掛載轉儲 - 或者只是在調試器中運行 - 併發布了結果,它確實會有所幫助。只是說它「凍結我的應用程序」意味着每個人都必須猜測可能發生了什麼問題。在這種情況下,結果很可能是未處理的'NSRangeException',但這只是一個猜測;調試器會告訴你,肯定的是,這會讓答案變得明顯。 – abarnert

+0

Abarnet,對不起。你是對的。我應該更具體。我仍然在學習XCode調試器的方法。 – ehsteve

回答

0

這裏是我終於可以實現這一點。爲了在數字爲負數時更清晰可見,我決定將文本的背景用白色文本表示爲紅色。下面的代碼在NSTextField單元中工作。我不確定爲什麼我的問題(和答案)中的代碼不起作用,addAttribute應該可以工作。

- (NSAttributedString *)attributedStringForObjectValue:(id)anObject withDefaultAttributes: (NSDictionary *)attributes{ 

    NSString *string = [self stringForObjectValue:anObject]; 
    NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:string]; 
    NSInteger stringLength = [string length]; 

    if ([[attrString string] floatValue] < 0) 
    { 
     NSDictionary *firstAttributes = @{NSForegroundColorAttributeName: [NSColor whiteColor], 
             NSBackgroundColorAttributeName: [NSColor blueColor]}; 
    [attrString setAttributes:firstAttributes range:NSMakeRange(0, stringLength)]; 
} 

return attrString; 
} 
3

我認爲這與您創建的NSRange有關。我相信你的長度(在你的例子中是10)是超出界限的。嘗試獲取用於初始化您的NSMutableAttributedString的字符串的長度。

例如:

- (NSAttributedString*) attributedStringForObjectValue: (id)anObject withDefaultAttributes: (NSDictionary*)attr; 
{ 
    NSString *string = [self stringForObjectValue:anObject]; 
    NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:string]; 
    NSInteger stringLength = [string length]; 

    if ([[attrString string] floatValue] < -20.0f) 
    { 
     [attrString addAttribute:@"NSForegroundColorAttributeName" value:[NSColor redColor] range:NSMakeRange(0, stringLength)]; 
    } 

    return attrString; 
} 
+0

+1。 [documentation](https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSMutableAttributedString_Class/Reference/Reference.html)明確指出「引發... NSRangeException」(如果有的話) * aRange *超出了接收者角色的末尾。「 – abarnert

+0

我做了您建議的更改,我的應用程序不再「凍結」。謝謝!不幸的是,沒有顏色似乎適用於文本。該文本正在顯示在一個表單單元格中,並且與其關聯的自定義格式化程序。 – ehsteve

+0

也許您需要將屬性字符串對象記錄到控制檯,以便確保它與您所期望的相同。原諒我,我不熟悉NSAttributedStrings。 – groomsy