我一直在为iOS编写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

最佳答案

SearchButton方法引用当前类中的webView,但是它是将要呈现的新ViewController(您称为WebView),并且应包含UIWebView。因此,所提供的视图控制器上的UIWebView永远不会进入loadRequest。

创建UIViewController的子类以包含您的Web视图。 (将其称为MyWebViewController之类的东西)。它应该具有一个称为urlString的属性。确保将当前在情节提要中绘制的视图控制器的类更改为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];
}

07-24 09:43
查看更多