我试图通过子类NSNumberFormatter在Objective中编写自己的自定义格式化程序。具体来说,我想做的是使一个数字变成红色,如果它高于或低于某些值。苹果文档说
例如,如果希望以红色显示负财务金额,则此方法将返回一个属性为red text的字符串。在attributedStringForObjectValue: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;
}但是当我测试这个时,它所做的只是冻结我的应用程序。如有任何建议,将不胜感激。谢谢。
发布于 2013-05-28 14:26:27
下面是我最终能够实现这一目标的方式。为了使它在数字为负值时更加可见,我决定将文本的背景改为白色文本。下面的代码确实在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;
}发布于 2012-12-31 22:41:03
我相信这与您创建的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;
}https://stackoverflow.com/questions/14106521
复制相似问题