显然,这段代码没有意义(例如,url 不是 pushViewController 所要求的 UIViewController 等),但我们可以对您尝试执行的操作做出明智的猜测。我猜你是说你想让后退按钮像网络浏览器上的后退按钮一样,但你希望标准导航控制器为你处理这个问题。这意味着您还建议每次单击页面上的链接时,您都希望推送到另一个视图控制器以显示下一个网页(以便后退按钮可以带您回到上一个使用上一个网页查看控制器)。
如果这是您要问的,那可能不是一个好主意。这意味着每次您在 Web 浏览器中单击链接时,您都需要让您的 UIWebViewDelegate 方法 shouldStartLoadWithRequest 拦截该请求,而不是让当前的 UIWebView 满足该请求,而是推送使用 UIWebView 触发该页面的另一个视图控制器。可悲的是,这是大量的工作并且非常浪费内存资源。它也不适用于很多网页。归根结底,这不是一个好主意。
只需将按钮添加到托管UIWebView 的视图控制器,然后让UIWebView 完成所有它的魔力,就会容易得多。然后,您可以添加用户在 iOS 网络浏览器上期望的所有其他按钮(不仅是后退按钮,还有前进按钮,也许是主页按钮,也许是一个“操作”按钮,可让您在 safari 中打开页面,在 fb 上分享, 等等。随心所欲。但用户期望的不仅仅是“后退”按钮。
更新:
如果你真的想在用户点击链接时推送到另一个视图控制器,你可以拦截shouldStartLoadWithRequest,正如我之前提到的。但是,以下代码示例假定:
- 您已将视图控制器定义为 Web 视图的委托;和
- 您已经定义了一个
BOOL 实例变量loadFinished。
不管怎样,你可能想要这三个UIWebViewDelegate 方法:
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
if (!initialLoadFinished)
{
// if we're still loading this web view for the first time, then let's let
// it do it's job
return YES;
}
else
{
// otherwise, let's intercept the webview from going to the next
// html link that the user tapped on, and create the new view controller.
// I'm making the next controller by instantiating a scene from the
// storyboard. Because you may be using NIBs or because you have different
// class names and storyboard ids, you will have to change the following
// line.
ViewController *controller = [self.storyboard instantiateViewControllerWithIdentifier:@"webview"];
// I don't know how you're passing the URL to your view controller. I'm
// just setting a (NSString*)urlString property.
controller.urlString = request.URL.absoluteString;
// push to that next controller
[self.navigationController pushViewController:controller animated:YES];
// and stop this web view from navigating to the next page
return NO;
}
}
// UIWebView calls this when the page load is done
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
initialLoadFinished = YES;
}
// UIWebView calls this if the page load failed. Note, though, that
// NSURLErrorCancelled is a well error that some web servers erroneously
// generate
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
if (error.code != NSURLErrorCancelled)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Web Loading Error"
message:nil // error.localizedDescription
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alert show];
initialLoadFinished = YES;
}
}
就我个人而言,我可能会坚持使用标准的UIWebView,但如果你想跳转到导航控制器,这可以做到。顺便说一句,上面的 hack 可能无法很好地处理重定向,所以请确保你的 URL 是正确的。