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
The code is the UITextField delegate method. Before you use this snippet, you must have these properties:
self.maxCharactersself.numeric // Only int characters.self.decimalNumeric // Only numbers and ".", "," (for specific locales, like Russian).- (BOOL)textField:(UITextField *) textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if(self.numeric || self.decimalNumeric)
{
NSString *fulltext = [textField.text stringByAppendingString:string];
NSString *charactersSetString = @"0123456789";
// For decimal keyboard, allow "dot" and "comma" characters.
if(self.decimalNumeric) {
charactersSetString = [charactersSetString stringByAppendingString:@".,"];
}
NSCharacterSet *numbersOnly = [NSCharacterSet characterSetWithCharactersInString:charactersSetString];
NSCharacterSet *characterSetFromTextField = [NSCharacterSet characterSetWithCharactersInString:fulltext];
// If typed character is out of Set, ignore it.
BOOL stringIsValid = [numbersOnly isSupersetOfSet:characterSetFromTextField];
if(!stringIsValid) {
return NO;
}
if(self.decimalNumeric)
{
NSString *currentText = [textField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
// Change the "," (appears in other locale keyboards, such as russian) key ot "."
currentText = [currentText stringByReplacingOccurrencesOfString:@"," withString:@"."];
// Check the statements of decimal value.
if([fulltext isEqualToString:@"."]) {
textField.text = @"0.";
return NO;
}
if([fulltext rangeOfString:@".."].location != NSNotFound) {
textField.text = [fulltext stringByReplacingOccurrencesOfString:@".." withString:@"."];
return NO;
}
// If second dot is typed, ignore it.
NSArray *dots = [fulltext componentsSeparatedByString:@"."];
if(dots.count > 2) {
textField.text = currentText;
return NO;
}
// If first character is zero and second character is > 0, replace first with second. 05 => 5;
if(fulltext.length == 2) {
if([[fulltext substringToIndex:1] isEqualToString:@"0"] && ![fulltext isEqualToString:@"0."]) {
textField.text = [fulltext substringWithRange:NSMakeRange(1, 1)];
return NO;
}
}
}
}
// Check the max characters typed.
NSUInteger oldLength = [textField.text length];
NSUInteger replacementLength = [string length];
NSUInteger rangeLength = range.length;
NSUInteger newLength = oldLength - rangeLength + replacementLength;
BOOL returnKey = [string rangeOfString: @"\n"].location != NSNotFound;
return newLength <= _maxCharacters || returnKey;
}
