I am using:
cleanedDataCellR2C2 = [cleanedDataCellR2C2 stringByReplacingOccurrencesOfString:@"," withString:@""];
and a whole bunch of similar satements to remove all keyboard characters from a textfield, except the digits…. – (the minus sign), + (the plus sign), as well as 0,1,2,3,4,5,6,7,8, and 9 numbers in a text field. The example above simply converts a comma in an NSString to a null value.
Hate to admit it, but in one project, I’m actually using about 80 statements — one for every keyboard character except those shown above. Thee must be some easier way. What would you suggest to do this job?
The best solution is to not let them enter non-numeric data in the first place, if you can. Are you using a
UITextField? If not, ignore the rest of this, but if so:First, make your view controller is a
UITextFieldDelegate, e.g.:and then later, in
viewDidLoad:Second, add a
shouldChangeCharacterInRangeto only allow the desired characters:Third, you might want to change your text field’s keyboard to be for numeric data only, e.g.
self.myTextField.keyboardType = UIKeyboardTypeNumbersAndPunctuationorUIKeyboardTypeDecimalPador something like that.