Adding a simple WebView to a view

In #ViewController.h

	IBOutlet UIWebView *webView1;
In Interface Builder

Drag the Web View onto the view
Connect the webView outlet to it

Displaying an Internet URL

E.g. in #ViewController.m ViewDidLoad:


	NSString *urlAddress = @"http://www.google.com";
	NSURL *url = [NSURL URLWithString:urlAddress];
	NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
	[webView1 loadRequest:requestObj];

Setting The Zoom Level Of A Web View


	[myWebView stringByEvaluatingJavaScriptFromString:@"document. body.style.zoom = 0.5;"];

Scrolling A Web View


	int scroll=20; //Pixels to scroll
	NSString* s=[[NSString alloc] initWithFormat:@"window.scrollTo(0, %i)",scroll];
	[webView stringByEvaluatingJavaScriptFromString:s];

Displaying Rich Text In A Web View

A useful way of displaying rich text labels etc.

If you are using a webview as a label ensure you select it in the viewcontroller and turn off “user interaction enabled”, otherwise it will be dragable etc


     NSString *MyHtml = @"<html><head><title></title><style type=\"text/css\">BODY {font-family:georgia; font-size: 14px;}</style></head><body>";       //Set default font
     MyHtml = [MyHtml stringByAppendingString:@"<p>Some sample HTML text <strong>bold</strong>, <u>underlined</u>, <span style=\"color:#FF0000\">colored</span>.</p>"];
     MyHtml = [MyHtml stringByAppendingString:@"</body></html>"];       //The text to display
     [webView1 loadHTMLString:MyHtml baseURL:[NSURL URLWithString:@"http://www.google.com"]];     //The baseURL allows relative URLs within a document and can just use a dummy value

Note that even doing this is in viewDidLoad (the earliest point for a view) the web view typically won’t load until the view has been shown the first time (i.e. slid into view) – very annoying.  You can’t force a webview to load before a view is shown, so if you want to do it you have to do it programmatically:

http://www.iphonedevsdk.com/forum/iphone-sdk-development-advanced-discussion/14400-preload-webview.html