kiri
kiri

Reputation: 2007

textDidChange method called twice when click on Clear button in UISearch bar

I am using iOS7 i have a search bar. i am using textDidChange method to get each character and handling my code, I have clear "X button" when we have text. in previous versions when click on the clear button textDidChange method is called once and we used to handle the code there.

But in iOS7 this method is called twice when clicking on clear button , This behaviour i can see in Sample code also

Upvotes: 2

Views: 1238

Answers (4)

Adrian Ortuzar
Adrian Ortuzar

Reputation: 1

When you are working in the simulator and you type with the keyboard of your computer in the search bar, sometimes is calling twice to the method

-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)newText.

To avoid this problem you have to use the simulator keyboard. Looks like it is a simulator bug.

Upvotes: 0

vinylDeveloper
vinylDeveloper

Reputation: 707

I have the same issue, I solved it by creating a ivar... This worked for me because I reload my table after calling this and I reset textDidClear = NO; in my reloadTable method.

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    if (([searchText isEqualToString:@""]) && (textDidClear == NO))
    {
        textDidClear = YES;
        [_categoryManager loadCategoriesWithToken:nil];

    } else if (textDidClear == NO) {
        textDidClear = NO;
        [_productManager loadProductsFromSearch:searchText tokenIdent:nil];
    }
}

Upvotes: 0

user3347984
user3347984

Reputation: 31

You can create a private property:

@property (strong, nonatomic) NSString *searchedText;

and use it to check for equality:

-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)newText{
    if(![self.searchedText isEqualToString:newText]){ 
        self.searchedText = [[NSString alloc] initWithString:newText];
        //Do your magic
    }
}

Upvotes: 3

Antonio MG
Antonio MG

Reputation: 20410

I just tried myself and it's true, the method is called twice with the exact same parameters. Reading the documentation it doesn't say anything about it, so it may be just a bug.

Can you ignore it?

Upvotes: 4

Related Questions