2011-01-06 8 views
0

textFieldDidEndEditingでtxtFieldの内容を操作しようとしています。私たちがしたいことは、コンテンツ全体を左に回転させ、最後に現在の文字を追加することです。 これは、ユーザーが小数点なしで金額を入力できるようにするためです。iPhone SDK:txtFieldを操作する方法

これは私たちがこれまで行ってきたことですが、これがこれに最も効果的なアプローチであるかどうかはわかりません。また、このコードは期待通りに動作しません。

助けてください。これにアプローチする無数の方法のうち

//easier input for total 
if (textField == txtGrandTotal) 
{ 
    //copy contents of total to string2 
    NSString *string1 = txtGrandTotal.text; 
    NSMutableString *string2; 

    //now string2 contains the buffer to manipulate 
    string2 = [NSMutableString stringWithString: string1]; 

    //so, copy it to strMoney2 
    strMoney2 = string2; 

    int charIndex; 
    //for all character in strMoney2, move them rotated left to strMoney1 
    for (charIndex = 0; charIndex < [strMoney2 length]; charIndex++) 
    { 
     NSString *strChar = [strMoney2 substringWithRange: NSMakeRange(charIndex, 1)]; 
     [strMoney1 insertString:strChar atIndex:charIndex+1]; 
    } 

    //now append the current character to strMoney1 
    NSString *strCurrentChar = [string1 substringWithRange: NSMakeRange([string1 length], 1)];  
    [strMoney1 appendString:strCurrentChar]; 


    //move manipulated string back to txtGrandTotal 
    txtGrandTotal.text = strMoney1; 
} 

答えて

1

、これは非常に短いです:

NSString *res = [NSString stringWithFormat:@"%@%@", 
    [input substringFromIndex:1], 
    [input substringToIndex:1] 
]; 

または短い:

NSString *res = [[input substringFromIndex:1] 
         stringByAppendingString:[input substringToIndex:1]]; 
+0

PS。これは大規模なループではありません。独自の 'NSAutoreleasePool'を作成せずに、それらの一時的な' NSString'オブジェクトをすべて解放してください。 – mvds

関連する問題