我在我的应用上创建了一个搜索选项,当搜索栏中输入查询并按下搜索按钮时,它会显示结果。但是当我再次尝试时,它不会搜索。我将留在最后的结果。
以下是按下搜索按钮时激活的代码。
-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
NSString *query = [googleBar.text stringByReplacingOccurrencesOfString:@" " withString:@"+"];
UIWebView *webview3=[[UIWebView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http:/server.bithumor.co/search/index1.php?query=%@", query]];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[webview3 loadRequest:request];
[self.view addSubview:webview3];
[self.view sendSubviewToBack:webview3];
webview3.scrollView.bounces = NO;
[self webviewListen:webview3];
[searchBar resignFirstResponder];
}
- (void)viewDidLoad {
_barButton.target = self.revealViewController;
_barButton.action = @selector(revealToggle:);
[self.view addGestureRecognizer:self.revealViewController.panGestureRecognizer];
googleBar.delegate = self;
}
为什么这在第一次之后无法正常工作?如何解决?
答案 0 :(得分:1)
不要为每次搜索反复添加webview。
请尝试以下步骤。
i)声明webview属性
@property (nonatomic, strong) UIWebView *webView;
ii)在ViewDidLoad方法中添加webview。
CGRect frame = self.view.bounds;
frame.origin.y = CGRectGetMaxY(self.searchBar.frame);
frame.size.height = CGRectGetHeight(self.view.bounds) - CGRectGetHeight(self.searchBar.bounds);
self.webView =[[UIWebView alloc]initWithFrame:frame];
[self.view addSubview:self.webView];
[self.view bringSubviewToFront:self.webView];
[self.view bringSubviewToFront:self.searchBar];
iii)在searchBarSearchButtonClicked方法中添加以下代码
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http:/server.bithumor.co/search/index1.php?query=%@", query]];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[self.webView loadRequest:request];
希望这有帮助。