2011-01-06 41 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 2011-01-06 17:30:12