Objective-c – UIWebView and navigation controller

iphoneobjective cuinavigationcontrolleruiwebviewxcode

How can I tell my UIWebView to open links in a new View , using a UINavigationController ?

I found this thread, but i m a little confused of where to implement that piece of code (i m new to objective-C/IPhone)

Clicking a link in UIWebView pushes onto the NavigationView stack

my view just contains a simple WebView with a UINavigationController on top

#import <UIKit/UIKit.h>


@interface ContactViewController : UIViewController {

    IBOutlet UIWebView *webView1;
}

@property (nonatomic, retain) UIWebView *webView1;

Best Answer

Here are steps assuming your view controller (that houses the webview) is already within a navigation controller.

Within the .h - ensure your view controller conforms to the webview delegate

UIViewController <UIWebViewDelegate>

Within the .m - add the following code (or just implement this method with whatever logic you want)

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
if (navigationType == UIWebViewNavigationTypeLinkClicked) {
    YourNextViewController *ynvc = [[[YourNextViewController alloc] initWithNibName:@"YourNextViewController" bundle:nil] autorelease];
    ynvc.ivar1 = value1;
    ynvc.ivar2 = value2;

    UIBarButtonItem *backButton = [[[UIBarButtonItem alloc] initWithTitle:@"Back" style:UIBarButtonItemStyleBordered target:nil action:nil] autorelease];
    [[self navigationItem] setBackBarButtonItem:backButton];

    [self.navigationController pushViewController:ynvc animated:YES];

    return NO;
}
return YES;}