Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 571
Sahil Tyagi Avatar asked Apr 15 '12 12:04

Sahil Tyagi


2 Answers

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)
like image 118
Felix Avatar answered Oct 21 '22 21:10

Felix


The most convenient delegate method to retrieve the new text from is:

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText

Both [searchBar text] and searchText will return the newly typed text. shouldChangeTextInRange intentionally reports the old text because it permits you to cancel the edit before it happens.

like image 29
Cowirrie Avatar answered Oct 21 '22 19:10

Cowirrie