明らかに、このコードは意味を成しません (たとえば、 が必要とする でurl
はないなど)。戻るボタンを Web ブラウザーの戻るボタンのように動作させたいと言っているのだと思いますが、標準のナビゲーション コントローラーでそれを処理してもらいたいのです。つまり、ページ上のリンクをクリックするたびに、別のView Controllerにプッシュして次のWebページを表示することを提案しているということです(戻るボタンで前のページに戻ることができます)以前の Web ページでコントローラーを表示します)。UIViewController
pushViewController
それがあなたが求めているものである場合、それはおそらく良い考えではありません。つまり、Web ブラウザーでリンクをクリックするたびに、UIWebViewDelegate
メソッドでshouldStartLoadWithRequest
その要求をインターセプトし、現在のUIWebView
要求を満足させるのではなく、UIWebView を起動して別のビュー コントローラーにプッシュする必要があります。そのページ。残念なことに、これは大変な作業であり、メモリ リソースを非常に浪費します。また、多くの Web ページでは機能しません。要するに、素晴らしいアイデアではないでしょう。
をホストするView Controllerにボタンを追加するだけで、UIWebView
魔法UIWebView
のようにすべてを実行する方がはるかに簡単です。次に、ユーザーが iOS Web ブラウザーで期待するようになった他のすべてのボタンを追加できます (戻るボタンだけでなく、進むボタン、おそらくホーム ボタン、サファリでページを開き、fb で共有できる「アクション」ボタンなど)。しかし、ユーザーは単なる「戻る」ボタン以上のものを期待しています。
アップデート:
ユーザーがリンクをクリックしたときに本当に別のView Controllerにプッシュしたい場合は、shouldStartLoadWithRequest
前述のようにインターセプトできます。ただし、次のコード サンプルでは次のことを前提としています。
- ビュー コントローラーを Web ビューのデリゲートとして定義しました。と
BOOL
インスタンス変数を定義しましたloadFinished
。
とにかく、おそらく次の 3 つの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
が、ナビゲーションコントローラーにジャンプしたい場合は、これで十分です。ところで、上記のハックではリダイレクトが適切に処理されない可能性があるため、URL が正しいことを確認してください。