xcode 如何在键入时获取搜索栏的当前字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10161833/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get current string of search bar while typing
提问by Sahil Tyagi
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.
但它正在返回前一个字符串。例如,我输入“jumbo”时,它会显示“jumb”,当我按退格键删除一项并将其设置为“jumb”时,它会显示“jumb”。即搜索栏上的前一个字符串。
What should I do to get the current string? plsease help. Thanks
我该怎么做才能获得当前字符串?请帮忙。谢谢
回答by Felix
Inside the method you get the entered text with:
在该方法中,您可以使用以下命令获取输入的文本:
NSString* newText = [searchBar.text stringByReplacingCharactersInRange:range withString:text]
Swift 3:
斯威夫特 3:
let newText = (searchBar.text ?? "" as NSString).replacingCharacters(in: range, with: text)
回答by Dondragmer
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.
双方[searchBar text]
并searchText
会返回新键入的文本。 shouldChangeTextInRange
故意报告旧文本,因为它允许您在编辑发生之前取消编辑。
回答by Mat
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;
}
回答by lenooh
Swift 3 version:
斯威夫特 3 版本:
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String){
print("searchText: \(searchText)")
}
This will fire whenever the text changes in the searchbar.
每当搜索栏中的文本更改时,这都会触发。
回答by Atul Pol
Swift 4.2
斯威夫特 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
}