Sahil Tyagi
Sahil Tyagi

Reputation: 363

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

Upvotes: 9

Views: 8496

Answers (5)

Atul Pol
Atul Pol

Reputation: 351

Swift 4.2

func searchBar(_ searchBar: UISearchBar, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
        let newString = NSString(string: searchBar.text!).replacingCharacters(in: range, with: text)

        return true
    }

Upvotes: 2

Felix
Felix

Reputation: 35384

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)

Upvotes: 13

lenooh
lenooh

Reputation: 10682

Swift 3 version:

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String){
    print("searchText: \(searchText)")
}

This will fire whenever the text changes in the searchbar.

Upvotes: 1

Cowirrie
Cowirrie

Reputation: 7226

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.

Upvotes: 5

Mat
Mat

Reputation: 7633

Try with:

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

Upvotes: 4

Related Questions