This short post is a tutorial on how to embed a specified webpage on the screen using the UIWebView class. This class includes several methods to load web content and several properties to control how the web page is displayed inside the window.
The screenshot shows a simple example where I embed the exact same web page (http://www.joshiscorner.com) in two different UIWebView objects:
STEP 1: Set up the storyboard
Drag two UIWebView objects to the storyboard and size both views to be 280 by 250.
STEP 2: Make connections
Make IBOutlet connections by ctrl-clicking from the UIWebViews on the storyboard to the ViewController interface.
STEP 3: Specify the URL and display it inside the window
The ViewController implementation is copied below.
#import "ViewController.h" @interface ViewController () @property (strong, nonatomic) IBOutlet UIWebView *webView1; @property (strong, nonatomic) IBOutlet UIWebView *webView2; @end @implementation ViewController @synthesize webView1; @synthesize webView2; - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. NSString *string = @"http://www.joshiscorner.com"; NSURL *url = [NSURL URLWithString:string]; NSURLRequest *request = [NSURLRequest requestWithURL:url]; [webView1 loadRequest:request]; [webView2 loadRequest:request]; webView2.scalesPageToFit = YES; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } @end
As usual, we synthesize the two UIWebView properties and then use the NSURL class to specify the URL we wish to load. In this case, we load the same URL in both the windows. But in the top window, we load the page “as is”, that is using the width specified in the HTML/CSS on the remote server. In this case, the width of the page is set to 970px, while the width of the iPhone screen is 320px. So when we display the page “as is”, only a fraction of the content is seen inside the window.
In the second view, we use the “scalesPageToFit” property of the UIWebView object and set it to YES. This forces the view to display the entire width of the web page.
You can learn more about the UIWebView class on the Apple Developer website.