iPhone SDK:如何操纵txtField
问题描述:
尝试在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;
}
答
出的无数的方式接近这一点,这是很短:
NSString *res = [NSString stringWithFormat:@"%@%@",
[input substringFromIndex:1],
[input substringToIndex:1]
];
或更短:
NSString *res = [[input substringFromIndex:1]
stringByAppendingString:[input substringToIndex:1]];
PS。不要这样做是一个很大的循环,不要创建自己的'NSAutoreleasePool'来释放所有这些临时的'NSString'对象。 – mvds 2011-01-06 17:30:12