Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UITextField Should accept number only values

I have UITexfields i want that it should accept only number other shows alert that enter a numeric value. I want that motionSicknessTextFiled should only accept number

NSString*dogswithMotionSickness=motionSicknessTextField.text; NSString*valueOne=cereniaTextField.text; NSString*valueTwo=prescriptionTextField.text; NSString*valueThree=otherMeansTextField.text; NSString*valueFour=overtheCounterTextField.text; 
like image 431
james Avatar asked May 24 '12 09:05

james


People also ask

How do I restrict TextField to numbers only?

Method 1: Changing the Text Field Type from storyboard. Select the text field that you want to restrict to numeric input. Go to its attribute inspector. Select the keyboard type and choose number pad from there.

How do I restrict TextField to numbers only flutter?

The TextField widget is required to set keyboardType: TextInputType. number, and inputFormatters: <TextInputFormatter>[FilteringTextInputFormatter. digitsOnly] to accept numbers only as input.


1 Answers

In whatever UITextField you're getting these values from, you can specify the kind of keyboard you want to appear when somebody touches inside the text field.

E.G. a numeric-only keyboard.

Like this screenshot:

numeric only keyboard will appear

This is easily set when working with the XIB and the Interface Builder built into Xcode, but if you want to understand this programmatically, take a look at Apple's UITextInputTraits protocol reference page, specifically the keyboardType property information.

To filter out punctuations, set the textfield's delegate and set up the shouldChangeCharactersInRange method:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {     NSCharacterSet *numbersOnly = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];     NSCharacterSet *characterSetFromTextField = [NSCharacterSet characterSetWithCharactersInString:textField.text];      BOOL stringIsValid = [numbersOnly isSupersetOfSet:characterSetFromTextField];     return stringIsValid; } 
like image 147
Michael Dautermann Avatar answered Oct 10 '22 11:10

Michael Dautermann