Search code examples
iosuisearchbaruisearchbardelegate

searchBarSearchButtonClicked doesn't work together with shouldChangeTextInRange


I have the following UISearchBar delegate method that works by its own (it's called when it's alone).

-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    [self downloadFruits:searchBar.text];
    [self.view endEditing:YES];
}

When I added another UISearchBar delegate method the previous one stopped working (it's not called anymore).

#define CHARACTERS @"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz _-."
#define CHARACTERS_NUMBERS  [CHARACTERS stringByAppendingString:@"1234567890"]

-(BOOL)searchBar:(UISearchBar *)searchBar shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    NSCharacterSet *unacceptedInput =
    [[NSCharacterSet characterSetWithCharactersInString:CHARACTERS_NUMBERS] invertedSet];
    // If array has more than one entry, there was at least one unacceptable character
    if ([[text componentsSeparatedByCharactersInSet:unacceptedInput] count] > 1)
        return NO;
    else
        return YES;
}

Each of them works well alone but together the first one (Search button) is not called


Solution

  • I think you should add \n to CHARACTERS

    #define CHARACTERS @"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz _-.\n"