iphone - UITextField 输入字符串更新

标签 iphone ios xcode ipad

我有一个文本框,我想用小键盘输入它。 我希望文本字段一开始像 00.00 一样,并且随着用户 strat 键入它从左到右或从右到左更新。例如,如果他键入 2 后跟 3,那么文本字段应该是 23.00,而且用户只允许输入小数点后最多 2 位数字的数字。 我怎样才能获得这个功能??

感谢进阶。

干杯, 西亚瓦什

最佳答案

.h

@property (assign, nonatomic) int maximumFractionDigits;
@property (strong, nonatomic) NSString* decimalSeparator;

loadViewviewDidLoad中放这个,

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/

相关文章:

ios - 我在哪里可以下载适用于 XCode 的 IOS DeviceSupport 16A5357B?

ios - 检测以纵向或横向全屏播放的视频

ios - 如何修复损坏的 iOS 模拟器(操作无法完成。LaunchServicesError 错误 0。)

ios - 从 Swift 中的非静态方法访问静态变量

Swift 编译不使用预编译头文件

iphone - 单击单元格时的 UITableViewCellAccessoryCheckmark

ios - 如何使 WebView 在 iPhone/iPad Retina 中工作

ios - 在 iOS 中使用 NSHost

iphone - 在 iOS 4 上运行 iOS 5 应用程序有困难

ios - CLGeocoder reverseGeocodeLocation 不适用于模拟位置