Travis Griggs
Travis Griggs

Reputation: 22252

How to configure a decimal numeric field for an iOS (iPhone) app?

I have an app that needs to include a field where the user can input a decimal scalar number. Is there a recipe for how to accomplish this? I've read the relevant parts in Matt Neuburg's "Programming iOS 7" book. I've tried a Cocoapod (MPNumericTextField). I'm not having a lot of luck...

What I've accomplished so far:

  1. Painted a UITextField in my storyboard.
  2. Given it an outlet and a delegate.
  3. Set its Keyboard Type to Decimal Pad.
  4. Implemented the following 3 methods:

    - (BOOL)textFieldShouldEndEditing:(UITextField *)textField {
        NSLog(@"textFieldShouldEndEditing:");
        [textField resignFirstResponder];
        return YES;
    }
    
    - (BOOL)textFieldShouldReturn:(UITextField *)textField {
        NSLog(@"textFieldShouldReturn:");
        [textField resignFirstResponder];
        return YES;
    }
    
    - (void)textFieldDidBeginEditing:(UITextField *)textField {
        NSLog(@"textFieldDidBeginEditing:");
        [textField selectAll: nil];
    }
    

It appears that I'll have to implement textField:shouldChangeCharactersInRange:replacementString: method to avoid duplicate decimal points being put in.

But I can't figure out how to dismiss/close the keyboard when I'm done inputting the number. What's the point of the Decimal Pad if you can't close it?

Are there other things I have to do get a simple numeric field working?

Upvotes: 0

Views: 144

Answers (2)

Zahid
Zahid

Reputation: 562

You will need to implement delegate like this to scan number and avoid double . in value.

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if (textField == _amountField) {
        NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
        if ([newString length] == 0) 
        {
            return YES;
        }

        double holder;

        NSScanner *scan = nil;

        scan = [NSScanner scannerWithString: newString];

        return ([scan scanDouble: &holder] && [scan isAtEnd]);
    }

    return YES;
}

Upvotes: 0

Vaibhav Jhaveri
Vaibhav Jhaveri

Reputation: 1605

Following line of code might serve your need

[self.view endEditing:YES];

Upvotes: 1

Related Questions