Code is not getting called

67 views Asked by At

In the method of shouldChnageTextInRange, I have a block of code validating a textField for currency input. I then tried getting an NSLog from a textField, but I never get results.

Here is my edited code I got from this answer:

- (BOOL) textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if (textField == self.myTextField)
    {
        static NSString *numbers = @"0123456789";
        static NSString *numbersPeriod = @"01234567890.";
        static NSString *numbersComma = @"0123456789,";   

        if (range.length > 0 && [string length] == 0) {
            // enable delete
            return YES;
        }

        NSString *symbol = [[NSLocale currentLocale] objectForKey:NSLocaleDecimalSeparator];
        if (range.location == 0 && [string isEqualToString:symbol]) {
            // decimalseparator should not be first
            return NO;
        }
        NSCharacterSet *characterSet;
        NSRange separatorRange = [textField.text rangeOfString:symbol];
        if (separatorRange.location == NSNotFound) {
            if ([symbol isEqualToString:@"."]) {
                characterSet = [[NSCharacterSet characterSetWithCharactersInString:numbersPeriod] invertedSet];
            }
            else {
                characterSet = [[NSCharacterSet characterSetWithCharactersInString:numbersComma] invertedSet];              
            }
        }
        else {
            // allow 2 characters after the decimal separator
            if (range.location > (separatorRange.location + 2)) {
                return NO;
            }
            characterSet = [[NSCharacterSet characterSetWithCharactersInString:numbers] invertedSet];               
        }
        return ([[string stringByTrimmingCharactersInSet:characterSet] length] > 0);
    }
    NSLog(@"%@", textField.text);
}

The last NSLog never gets called. What can I do to fix that? (I set the delegate to self.)

2

There are 2 answers

6
Reming Hsu On BEST ANSWER

You should put the code before return.

- (BOOL) textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    NSLog(@"%@", textField.text); //before return
    ...
}
0
Kaushal Kumar On

once method return it is not executed the next line code . in your code some little mistake correct it code NSLog(@"%@", textField.text); should before code return ([[string stringByTrimmingCharactersInSet:characterSet] length] > 0);