Set a range of numeric values ​​for a text field

I have a text box that should only accept a numerical value for a certain range, for example m to n. I looked through a lot of articles, but they all just say how to set the maximum length for a text field. But I need to set the text field so that it accepts values ​​only in the range, for example, from 23 to 103. I was able to make sure that the text field accepts only numerical values ​​by setting the keyboard type to the numeric keypad. Someone please help.

+4
source share
3 answers

You can check the value when the user has finished editing the text field.

Set the textField delegate to your view controller, and then:

- (BOOL)textFieldShouldReturn:(UITextField *)textField { NSString *stringValue = textField.text; NSInteger integer = [stringValue intValue]; if (integer <23 || integer > 103) // You can make the text red here for example return NO; else return YES; } 
+4
source

You usually achieve this using a proprietary number format that has a minimum / maximum valid value, for example:

 NSNumberFormatter* formatter= [[NSNumberFormatter alloc]init]; formatter.numberStyle= NSNumberFormatterDecimalStyle; formatter.allowsFloats= NO; formatter.maximum= @103; formatter.minimum= @23; 

Then allow the user to return only if the formatter returns a valid number:

 - (BOOL)textFieldShouldReturn:(UITextField *)textField { return [formatter numberFromString: textField.text]!= nil; } 
+1
source

Try it. If you want to set a range for a specific text field.

 - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string 

{

 if(textField == self.txtMobileNumber ) { if (textField.text.length >= 10 && range.length == 0) return NO; } } 
0
source

Source: https://habr.com/ru/post/1492044/


All Articles