首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >目标C中的定制NSFormatter

目标C中的定制NSFormatter
EN

Stack Overflow用户
提问于 2012-12-31 22:27:40
回答 2查看 501关注 0票数 0

我试图通过子类NSNumberFormatter在Objective中编写自己的自定义格式化程序。具体来说,我想做的是使一个数字变成红色,如果它高于或低于某些值。苹果文档

例如,如果希望以红色显示负财务金额,则此方法将返回一个属性为red text的字符串。在attributedStringForObjectValue:withDefaultAttributes:中,通过调用stringForObjectValue:获取非属性化字符串,然后将正确的属性应用于该字符串。

基于此建议,我实现了以下代码

代码语言:javascript
复制
- (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;
}

但是当我测试这个时,它所做的只是冻结我的应用程序。如有任何建议,将不胜感激。谢谢。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-05-28 14:26:27

下面是我最终能够实现这一目标的方式。为了使它在数字为负值时更加可见,我决定将文本的背景改为白色文本。下面的代码确实在NSTextField单元格中工作。我不知道为什么我问题中的代码(以及答案)不能工作,addAttribute应该工作。

代码语言:javascript
复制
- (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;
}
票数 0
EN

Stack Overflow用户

发布于 2012-12-31 22:41:03

我相信这与您创建的NSRange有关。我相信你的长度(在你的例子中是10)是超出范围的。尝试获取用于初始化NSMutableAttributedString的字符串的长度。

例如:

代码语言:javascript
复制
- (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;
}
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14106521

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档