0

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

1 回答 1

1

SearchButton 方法是指当前类中的一个 webView,但它是即将呈现的新 ViewController(你称之为 WebView),它应该包含一个 UIWebView。所以呈现的视图控制器上的 UIWebView 永远不会加载请求。

创建 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];
}
于 2013-06-19T06:09:03.670 回答