如何在iphone中使textfield接受十进制输入

时间:2012-06-20 05:56:06

标签: iphone xcode uitextfield

我有一个计算器应用程序,我有一个文本字段,如果我输入任何数字;然后它工作正常。如果我没有输入数字,那么它会显示警报。我还希望用户能够输入1.5但是当我这样做时它会显示警告“请输入一个号码”

那么如何输入十进制数?我使用以下代码:

   NSCharacterSet * set = [[NSCharacterSet characterSetWithCharactersInString:@"0123456789"] invertedSet];


  NSString*string=costToClientTextField.text;

 if ([string rangeOfCharacterFromSet:set].location != NSNotFound) {


 UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"Warning" message:@"Only a number can be entered into this input field " delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
 [alert show];
 [alert release];


 costToClientTextField.text=@"";


  }

2 个答案:

答案 0 :(得分:0)

添加“。”在你的集合中,像这样

  NSCharacterSet * set = [[NSCharacterSet characterSetWithCharactersInString:@"0123456789."] invertedSet];

答案 1 :(得分:0)

- (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;
    }
}

也许这会对你有所帮助。还放了键盘型号和标点符号。