我一直在为iOS编写一个Web浏览器应用程序,偶然发现了一个问题。首先我的搜索文本字段和Web视图在同一视图中(一切都很好:)。当我将Web视图放在不同的视图中时,Web视图不会加载页面并保持空白。所以问题是Web视图不会加载到不同的视图中(如果文本字段和Web视图在同一视图中,则会起作用)。
我的代码:
#import "ViewController.h"
#import <QuartzCore/QuartzCore.h>
@interface ViewController ()
@end
@implementation ViewController
@synthesize searchButton;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib
}
-(IBAction)SearchButton:(id)sender {
NSString *query = [searchField.text stringByReplacingOccurrencesOfString:@" " withString:@"+"];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://www.google.com/search?q=%@", query]];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[webView loadRequest:request];
ViewController *WebView = [self.storyboard instantiateViewControllerWithIdentifier:@"WebView"];
[self presentViewController:WebView animated:YES completion:nil];
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[self.view endEditing:YES];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
答案 0 :(得分:1)
SearchButton方法引用当前类中的webView,但它是即将呈现的新ViewController(您称之为WebView),它应包含UIWebView。因此,呈现的视图控制器上的UIWebView永远不会进入loadRequest。
创建UIViewController的子类以包含您的Web视图。 (称之为MyWebViewController)它应该有一个名为urlString的属性。确保将当前在storyboard中绘制的视图控制器的类更改为MyWebViewController。
SearchButton方法应如下所示:
// renamed to follow convention
- (IBAction)pressedSearchButton:(id)sender {
NSString *query = [searchField.text stringByReplacingOccurrencesOfString:@" " withString:@"+"];
NSString *urlString = [NSString stringWithFormat:@"http://www.google.com/search?q=%@", query];
// remember to change the view controller class in storyboard
MyWebViewController *webViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"WebView"];
// urlString is a public property on MyWebViewController
webViewController.urlString = urlString;
[self presentViewController:webViewController animated:YES completion:nil];
}
新类可以从urlString ...
形成请求// MyWebViewController.h
@property (nonatomic, strong) NSString *urlString;
@property (nonatomic, weak) IBOutlet UIWebView *webView; // be sure to attach in storyboard
// MyWebViewController.m
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
NSURL *url = [NSURL URLWithString:self.urlString];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[self.webView loadRequest:request];
}