Search code examples
iphoneobjective-cxcodeios5

How to get current string of search bar while typing


On pressing the searchbar I want to get the string that has already been entered. For that I am currently using this method:

- (BOOL)searchBar:(UISearchBar *)searchBar shouldChangeTextInRange:(NSRange)range     replacementText:(NSString *)text
{
    NSLog(@"String:%@",mainSearchBar.text);
    return YES;
}

But it is returning the previous string. For example id i type "jumbo", it shows jumb and when i press backspace to delete one item and make it "jumb", it shows jumbo. i.e the previous string on the searchbar.

What should I do to get the current string? plsease help. Thanks


Solution

  • Inside the method you get the entered text with:

    NSString* newText = [searchBar.text stringByReplacingCharactersInRange:range withString:text]
    

    Swift 3:

    let newText = (searchBar.text ?? "" as NSString).replacingCharacters(in: range, with: text)