How to get current string of search bar while typing
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
}
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;
}
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.
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)