Simple way to control the initial appearance of a UIWebView

Recently, I was working with a UIWebView and noticed some odd behavior. I needed to display some information that comes through an API as HTML; UIWebView to the rescue. In an attempt to blend it into the background of the page while the content was loading, I set the background color property to black.

The problem was it just didn’t work, the UIWebView would always load with a default gray background overriding the underlying UIView’s background color. Finally when the real content finished loading, the HTML background color of my content would kick in and it would blend into the page perfectly.

It was annoying behavior, but nothing to go crazy about. Later while I was working other more urgent problems, I came up with a super simple solution and though I would share. By simply pre-loading the view with some HTML and some optional CSS you get some powerful control over how the UIWebView appears while loading your real content. In my View Controller’s viewDidLoad method I added this:

- (void) viewDidLoad {
NSString *loadingHTML = [NSString stringWithFormat:@"<html><body style=\"background-color:#000;color:#FFF;font-family:Helvetica;font-size:14px;margin-left:0px\">Loading...</body></html>"];
[yourWebView loadHTMLString:loadingHTML baseURL:nil];

Adding this to the viewDidLoad method ensures the HTML is loaded before it’s displayed on screen. It gave me control over the initial view color and let me add a loading message as well. I used CSS to match the font size/face to the other text on the page, but because it’s HTML and CSS the possibilities are nearly endless.

Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s