UIWebView in iOS

Mr.Javed Multani
2 min readOct 3, 2020

Create a UIWebView instance


let webview = UIWebView(frame: CGRect(x: 0, y: 0, width: 320, height: 480))


UIWebView *webview = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];//Alternative way of defining frame for UIWebViewUIWebView *webview = [[UIWebView alloc] init];
CGRect webviewFrame = webview.frame;
webviewFrame.size.width = 320;
webviewFrame.size.height = 480;
webviewFrame.origin.x = 0;
webviewFrame.origin.y = 0;webview.frame = webviewFrame;

Determining content size

In many cases, for instance when using web views in table view cells, it’s important to determine the content size of the rendered HTML page. After loading the page, this can be calculated in the UIWebViewDelegate delegate method:

- (void) webViewDidFinishLoad:(UIWebView *) aWebView {
CGRect frame = aWebView.frame;
frame.size.height = 1;
aWebView.frame = frame;CGSize fittingSize = [aWebView sizeThatFits:CGSizeZero];
frame.size = fittingSize;
aWebView.frame = frame;NSLog(@"size: %f, %f", fittingSize.width, fittingSize.height);

The code employs an additional trick of shortly setting the height of the web view to 1 prior to measuring the fitting size. Otherwise it would simply report the current frame size. After measuring we immediately set the height to the actual content height.

Load HTML string

Web views are useful to load locally generated HTML strings.

NSString *html = @"<!DOCTYPE html><html><body>Hello World</body></html>";
[webView loadHTMLString:html baseURL:nil];


let htmlString = "<h1>My First Heading</h1><p>My first paragraph.</p>"
webView.loadHTMLString(htmlString, baseURL: nil)NSString *html = @"<!DOCTYPE html><html><head><link href='style.css' rel='stylesheet' type='text/css'></head><body>Hello World</body></html>";
[self loadHTMLString:html baseURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] resourcePath]]];

In this case, style.css is loaded locally from the app’s resource directory. Of course it’s also possible to specify a remote URL.

Making a URL request

Load content in webview from the url


webview.loadRequest(NSURLRequest(URL: NSURL(string: “http://www.google.com")!))


[webview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@”http://www.google.com"]]];
Mr.Javed Multani

Software Engineer | Certified ScrumMaster® (CSM) | UX Researcher | Youtuber | Tech Writer