You are looking at this problem incorrectly. When you setup a text field with the Decimal keypad, the keypad will show either a period or a comma depending on the user's locale. This is what you want. Some users will want to enter decimal numbers like 3.14
while other users will want to enter them as 3,14
.
Run the Settings app and go to General, then International. Look at the Region Format setting. This determines the user's locale and whether a period or comma is used. Your device and simulator must be setup with different region format settings.
Here's the final part - once a user enters a decimal value, you must use an NSNumberFormatter
to properly convert the string entered into the text field to an NSNumber
. The NSNumberFormatter
will properly deal with a comma or period in the number based on the user's locale. Also, when you need to show the number to the user, use an NSNumberFormatter
to convert the number to a string. This will ensure the number is displayed to the user in the format expected by the user.
Do not replace a comma with a period during user entry of the value. It will confuse the user.
Update
One thing you could do in the shouldChangeCharactersInRange
delegate method is to just be sure all the characters being entered are valid number characters. I would not do things like checking for two decimal separator characters. Just let the user type in number related characters.
You do the final validation when the user tries to leave the text field. Example:
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField {
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
NSNumber *val = [formatter numberFromString:textField.text];
return val != nil; // don't let the user leave if text is not a valid number
}