I am creating a text field.
Whenever the value in text field is greater than 100 I need to display an alert saying "value must be less than 100", then the text field's value should be cleared.
How can I do this?
An object that displays an editable text area in your interface.
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.
A text field is a rectangular area in which people enter or edit small, specific pieces of text.
You can have your view controller conform to the UITextFieldDelegate
protocol and implement the -textField:shouldChangeCharactersInRange:replacementString:
method:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
if (range.location == 0 && string.length == 0) {
return YES;
}
// Build up the resulting string…
NSMutableString *fullString = [[NSMutableString alloc] init];
[fullString appendString:[textField.text substringWithRange:NSMakeRange(0, range.location)]];
[fullString appendString:string];
// Set up number formatter…
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
NSNumber *replaceNumber = [formatter numberFromString:fullString];
[fullString release];
[formatter release];
return !(replaceNumber == nil || [replaceNumber intValue] > 100);
}
To build the full string you must take into account edits in the middle of the text field too. Made some changes to the code posted above.
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
BOOL result = NO;
// Build the final string...
NSMutableString *fullString = [[NSMutableString alloc] init];
NSUInteger firstChunkLength = range.location;
NSUInteger secondChunkStart = range.location + range.length;
NSUInteger secondChunkLength = [textField.text length] - secondChunkStart;
[fullString appendString:[textField.text substringWithRange:NSMakeRange( 0, firstChunkLength )]];
[fullString appendString:string];
[fullString appendString:[textField.text substringWithRange:NSMakeRange( secondChunkStart, secondChunkLength )]];
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
NSNumber *replaceNumber = [formatter numberFromString:fullString];
NSNumber *originalNumber = [formatter numberFromString:textField.text];
result = ( replaceNumber != nil && replaceNumber != originalNumber );
[fullString release];
[formatter release];
return result;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With