2011-07-03 29 views
1

我真的想实现一个类如'UILabel + formattedText',允许我执行一个方法,将很好地格式化文本在标签的可见显示中,但任何查看label.text的代码都只能看到未格式化的数字字符串。我知道这可能很简单。事情是,我似乎无法找到它的语法。这将如何工作?我试过这种方法在我的视图控制器,但我真的很喜欢它在一个标签

这里是我的视图控制器内的方法草稿:

- (void)UpdateLabels{ 
    if(!formatter){//initialize formatter if there isn't one yet. 
     formatter = [[NSNumberFormatter alloc] init]; 
     [formatter setNumberStyle:NSNumberFormatterDecimalStyle]; 
     [formatter setPositiveFormat:@",##0.##"]; 
     [formatter setNegativeFormat:@",##0.##"]; 
     [formatter setMaximumFractionDigits:15]; 
     [formatter setMaximumIntegerDigits:15]; 

    } 
    NSRange eNotation =[rawDisplay rangeOfString: @"e"];//if there's an 'e' in the string, it's in eNotation. 
    if ([rawDisplay isEqual:@"Error"]) { 
     [email protected]"Error"; 
     backspaceButton.enabled = FALSE; 
    }else if (eNotation.length!=0) { 
     //if the number is in e-notation, then there's no special formatting necessary. 
     display.text=rawDisplay; 
     backspaceButton.enabled =FALSE; 
    } else { 
     backspaceButton.enabled =([rawDisplay isEqual:@"0"])? FALSE: TRUE; //disable backspace when display is "0"    
     //convert the display strings into NSNumbers because NSFormatters want NSNumbers 
     // then convert the resulting numbers into pretty formatted strings and stick them onto the labels 
     display.text=[NSString stringWithFormat:@"%@", [formatter stringFromNumber: [NSNumber numberWithDouble:[rawDisplay doubleValue]]]];   
    } 
} 

所以我基本上要至少标签绘图功能,进入标签。顺便说一句,这段代码对MVC是否真实?这是我的第一次尝试。

此外,当我在这里时,我可能会问:这会进入e表示法,相对较少的数字作为双精度表示。但是当我试图改变双重的东西,比如longlong,我会得到非常奇怪的结果。我如何能够更精确地完成所有这些操作?

回答

1

我会建议写一个UILabel的子类。由于您只想更改文本的显示方式,因此您只需编写自定义的drawTextInRect:方法即可。它将使用格式self.text的值并绘制结果字符串。然后你只需要改变应该格式化的任何标签的类。

例子:

@interface NumericLabel : UILabel {} 
@end 

@implementation NumericLabel 
- (void)drawTextInRect:(CGRect)rect { 
    static NSNumberFormatter *formatter; 
    NSString *text = nil, *rawDisplay = self.text; 

    if(!formatter){ 
     //initialize formatter if there isn't one yet. 
    } 
    NSRange eNotation =[rawDisplay rangeOfString: @"e"];//if there's an 'e' in the string, it's in eNotation. 
    if ([rawDisplay isEqual:@"Error"]) { 
     text = @"Error"; 
    }else if (eNotation.length!=0) { 
     text = rawDisplay; 
    } else { 
     text=[formatter stringFromNumber: [NSNumber numberWithDouble:[rawDisplay doubleValue]]];           
    } 

    [text drawInRect:rect withFont:self.font lineBreakMode:self.lineBreakMode alignment:self.textAlignment]; 
} 
@end 
+0

当我问我是否应该做的是,上周,人们似乎并不喜欢......但是啊,这是相当不错...我只是了解这个东西,我很满意上面的代码甚至可以工作。我相信它可以做得更好,但那是未来。你可以给我一个代码示例来展示它的外观吗? –

+0

@Dave我添加了示例代码。我也改变了答案,以表明你应该使用'drawTextInRect:'而不是'drawRect:'。请注意,该示例不启用/禁用退格,因为视图不应该在MVC中执行此操作(并且您应该在显示视图之前执行该操作)。 – ughoavgfhw

+0

谢谢你。我想我已经想通了,但我猜不是。更改为自定义标签杀死了这段代码:'//动态显示调整大小。 self.numberOfLines = 1; self.adjustsFontSizeToFitWidth = YES; self.minimumFontSize = 15.0f;'在这个迭代中,我尝试坚持自定义标签的init方法...不行?我在哪里放? –

相关问题