1

我正在创建自定义 NumberPad

if (([[[UIDevice currentDevice] systemVersion] doubleValue] >= 4.1)) {
    inputBoxTextField.keyboardType = UIKeyboardTypeDecimalPad;
}

我的问题是,我只想显示一次点。

提前致谢。

4

3 回答 3

5

如果你想让用户只输入一个点,你可以使用委托方法

-(BOOL) textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string

并简单地检查 textField 是否已经包含一个点。

于 2011-09-11T14:45:34.300 回答
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; } }
于 2011-09-20T08:14:31.487 回答
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; 
}
于 2012-12-03T12:45:56.270 回答