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
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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With