Member-only story

UIWebView in iOS

Mr.Javed Multani
2 min readOct 3, 2020

--

Create a UIWebView instance

Swift

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

Objective-C

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

--

--

Mr.Javed Multani
Mr.Javed Multani

Written by Mr.Javed Multani

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

No responses yet