1

ラベルの表示表示でテキストを適切にフォーマットするメソッドを実行できる「UILabel+formattedText」のようなカテゴリを実装したいのですが、label.textを参照するコードでは、フォーマットされていない数値文字列のみが表示されます。私はこれがおそらく非常に単純であることを知っています。そのための構文が見つからないようです。それは正確にどのように機能しますか?

これが、ViewController内のメソッドのラフドラフトです。

- (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"]) {
        display.text=@"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に当てはまりますか?それは私の最初の試みです。

また、私がここにいる間、私は尋ねることもできます:これは、doubleとして比較的少数の桁でe表記になります。しかし、doubleをlonglongなどの他の何かに変更しようとすると、非常に奇妙な結果が得られます。どうすればより正確になり、これらすべての操作を実行できますか?

4

1 に答える 1

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
于 2011-07-03T05:39:56.563 に答える