Код является методом делегата UITextField
. Перед использованием этого фрагмента вы должны иметь следующие свойства:
self.maxCharacters
self.numeric
// Только int символов. self.decimalNumeric
// Только цифры и ".", "," (Для определенных языков, например, русского). - (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;
}
Проверьте каждый уровень на exist
, прежде чем смотреть на верхний уровень.
if (exists $ref->{A} and exists $ref->{A}{B} and exists $ref->{A}{B}{$key}) {
}
Если вы находите, что раздражает, вы всегда можете посмотреть на CPAN . Например, есть Hash::NoVivify
.
Довольно уродливо, но если $ ref - сложное выражение, которое вы не хотите использовать в повторяющихся тестах с существующими:
if ( exists ${ ${ ${ $ref || {} }{A} || {} }{B} || {} }{key} ) {