我有一个文本框,我想用小键盘输入它。 我希望文本字段一开始像 00.00 一样,并且随着用户 strat 键入它从左到右或从右到左更新。例如,如果他键入 2 后跟 3,那么文本字段应该是 23.00,而且用户只允许输入小数点后最多 2 位数字的数字。 我怎样才能获得这个功能??
感谢进阶。
干杯, 西亚瓦什
最佳答案
在.h
@property (assign, nonatomic) int maximumFractionDigits;
@property (strong, nonatomic) NSString* decimalSeparator;
在loadView
或viewDidLoad
中放这个,
NSNumberFormatter* numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
[numberFormatter setCurrencyCode:@"GBP"];
self.maximumFractionDigits = numberFormatter.maximumFractionDigits;
self.decimalSeparator = numberFormatter.decimalSeparator;
[numberFormatter release];
在 UITextFieldDelegate
方法中
- (BOOL)textField:(UITextField*)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString*)string {
// get current cursor position
UITextRange* selectedRange = [textField selectedTextRange];
UITextPosition* start = textField.beginningOfDocument;
NSInteger cursorOffset = [textField offsetFromPosition:start toPosition:selectedRange.start];
// Update the string in the text input
NSMutableString* currentString = [NSMutableString stringWithString:textField.text];
NSUInteger currentLength = currentString.length;
[currentString replaceCharactersInRange:range withString:string];
// Strip out the decimal separator
[currentString replaceOccurrencesOfString:self.decimalSeparator withString:@"" options:NSLiteralSearch range:NSMakeRange(0, [currentString length])];
// Generate a new string for the text input
int currentValue = [currentString intValue];
NSString* format = [NSString stringWithFormat:@"%%.%df", self.maximumFractionDigits];
double minorUnitsPerMajor = pow(10, self.maximumFractionDigits);
NSString* newString = [NSString stringWithFormat:format, currentValue / minorUnitsPerMajor];
textField.text = newString;
// if the cursor was not at the end of the string being entered, restore cursor position
if (cursorOffset != currentLength) {
int lengthDelta = newString.length - currentLength;
int newCursorOffset = MAX(0, MIN(newString.length, cursorOffset + lengthDelta));
UITextPosition* newPosition = [textField positionFromPosition:textField.beginningOfDocument offset:newCursorOffset];
UITextRange* newRange = [textField textRangeFromPosition:newPosition toPosition:newPosition];
[textField setSelectedTextRange:newRange];
}
return NO;
关于iphone - UITextField 输入字符串更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15802432/