我正在创建自定义NumberPad
if (([[[UIDevice currentDevice] systemVersion] doubleValue] >= 4.1)) {
inputBoxTextField.keyboardType = UIKeyboardTypeDecimalPad;
}
我的问题是,我想只显示一次点。
提前感谢。
答案 0 :(得分:5)
如果您想允许用户只输入一个点,您可以使用委托方法
-(BOOL) textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
只需检查textField是否已包含点。
答案 1 :(得分:4)
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
NSNumber* candidateNumber;
NSString* candidateString = [textField.text stringByReplacingCharactersInRange:range withString:string];
range = NSMakeRange(0, [candidateString length]);
[numberFormatter getObjectValue:&candidateNumber forString:candidateString range:&range error:nil];
if (([candidateString length] > 0) && (candidateNumber == nil || range.length < [candidateString length])) {
return NO;
}
else {
return YES; } }
答案 2 :(得分:1)
我使用以下代码。适合我,并且代码更少。
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
NSString *decimalSymbol = [numberFormatter decimalSeparator];
if(([textField.text rangeOfString:decimalSymbol].location != NSNotFound) &&
([string rangeOfString:decimalSymbol].location != NSNotFound)) {
return NO;
}
return YES;
}