How to get the current search string when typing

When I click on the search bar, I want to get a string that has already been entered. For this, I am currently using this method:

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

But it returns the previous line. For example, id I type "jumbo", it shows jumb and when I press backspace to remove one element and make it "jumb", it shows jumbo. those. previous line in the search bar.

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

+5
source share
4 answers

Inside the method, you will 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)
+12
source

The most convenient delegate method for extracting new text:

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

[searchBar text] searchText . shouldChangeTextInRange , .

+4

Try:

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

Swift 3 version:

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

This will work every time the text in the search bar changes.

0
source

All Articles