Question

I am trying to convert user input of a number from a UITextView (not a UITextField, for reasons that would take too long to go into) string into a number. While this has presented no problems when the user enters data via the decimal keyboard on the iPhone, with a bluetooth keyboard (or using the keyboard in the simulator, the user can enter non-numeric characters, or can hit the return key. This causes the NSNumberFormatter to return nil, which of course does me no good.

I am trying to figure out how to deal with this. Should I make a filter that extracts just that part of the input string that has allowable characters in it? Can anyone recommend an elegant/efficient way to deal with this problem?

Here is my code:

static NSNumberFormatter *numberFormatter;
if (numberFormatter==nil) {
        numberFormatter=[[NSNumberFormatter alloc] init];
        [numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
        [numberFormatter setLenient:YES];
}
self.value = [numberFormatter numberFromString:self.valueTextView.text];

As I said, if the user enter 42, or 42.5, this works fine, but if she enters 42.5<Return> (which can only be done from the keyboard) then self.value is nil. Note: I added the setLenient mode to try and cope with the problem, but to no avail.

I've checked other answers on Stack Overflow (a number of people have asked similar questions), but the answers I found just confirm that yes, NSNumberFormatter will only parse, not validate, and if it cannot parse it will return nil. This doesn't solve the problem. How do others deal with this? It must be a common problem...

Was it helpful?

Solution

You should implement the delegate method textView:shouldChangeTextInRange:replacementText:. In its implementation you should create the text that would exist if you allow the edit to complete and try getting a number from that text with your formatter. If you get a number, allow the edit. If not, refuse the edit.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top