无法在另一个视图控制器的WebView中显示URL

我有一个UITableViewController需要打开一个Web视图。

在我的function,我有:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { LinkViewController *linkViewController = [[LinkViewController alloc] initWithNibName:@"LinkViewController_iPhone" bundle:nil]; [linkViewController.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.google.com"]]]; [self.navigationController pushViewController:linkViewController animated:YES]; } 

我连接了所有网点,但没有得到任何警告,但是我没有看到页面拉起来。

但是,如果我在实际的LinkViewController文件中执行如下操作:

 - (void)viewDidLoad { [super viewDidLoad]; NSString *urlAddress = @"http://www.google.com"; //Create a URL object. NSURL *url = [NSURL URLWithString:urlAddress]; //URL Requst Object NSURLRequest *requestObj = [NSURLRequest requestWithURL:url]; //Load the request in the UIWebView. [self.webView loadRequest:requestObj]; } 

一切似乎都很好。 我不懂为什么 ?

你应该添加一个URL属性到你的LinkViewController 。 然后在你的表视图控制器,你做到这一点:

 - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { LinkViewController *linkViewController = [[LinkViewController alloc] initWithNibName:@"LinkViewController_iPhone" bundle:nil]; linkViewController.URL = [NSURL URLWithString:@"http://www.google.com"]; [self.navigationController pushViewController:linkViewController animated:YES]; } 

现在在你的LinkViewController中你可以:

 - (void)viewDidLoad { [super viewDidLoad]; //URL Requst Object NSURLRequest *requestObj = [NSURLRequest requestWithURL:self.URL]; //Load the request in the UIWebView. [self.webView loadRequest:requestObj]; } 

原来有两个问题:

  1. 在表视图控制器中,您在初始化之前正在访问webView属性。 这就是为什么没有发生。
  2. 您将LinkViewController实现细节LinkViewController给外部世界。 如果您在应用程序的许多地方使用LinkViewController ,则需要该类的每个用户知道创buildURL,创build请求,然后告诉内部Web视图开始加载。 所有这些逻辑都属于LinkViewController 。 现在每个类的用户只需要知道设置一个简单的URL属性。