ChaniBlog











{August 30, 2013}   UIWebView css theming

For one of our apps at SteamClock, We’re switching from a dark to a light theme for iOS 7. We’re still keeping the dark theme for iOS 6, though. This has been a bit of a pain, and today I had the “fun” of figuring out how to theme our about page, written in html. :P It took about three stackoverflow answers and a blog post for me to piece together working code, so I’m adding Yet Another blog with a solution that’s more robust (so long as your theme doesn’t change while you’re displaying it).

The gist of it is, we use external css files (something the internet was unclear on too) and then edit the html string so that it loads the correct css file for the theme.

Here’s the line of html that loads the css:

   <link rel='stylesheet' href='about-THEME.css' />

Note the lack of a leading slash in the href. It broke when I added one. Oh, and of course I’m confident that ‘THEME’ will never appear elsewhere in my html.

Now, the ios code…

First, we load the html from our resource:

        NSString *htmlPath = [[NSBundle mainBundle] pathForResource:@"about" ofType:@"html"];
        NSData *htmlData = [NSData dataWithContentsOfFile:htmlPath];
        NSString *htmlString = [[NSString alloc] initWithData:htmlData encoding:NSUTF8StringEncoding];

Pretty straightforward.

Then, we swap out the ‘THEME’ placeholder for the right name:

        NSString *themeName = IS_IOS7 ? @"light" : @"dark";
        htmlString = [htmlString stringByReplacingOccurrencesOfString:@"THEME" withString: themeName];

That IS_IOS7 macro boils down to:
([[[UIDevice currentDevice] systemVersion] compare:@"7.0" options:NSNumericSearch] != NSOrderedAscending)

Now we need a base url so that it looks for the css file in the right place:

        NSURL *baseURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]];

Finally, we load the page:

        [self.webView loadHTMLString:htmlString baseURL:baseURL];

And that’s it! (well… almost. you may want to set the backgroundColor of the webView to match your css background, so that it looks nice while scrolling and such.)

Now our about page automagically fits the theme, and as an added benefit, all our translations share the same css instead of having it c&p’d into the html files. :)



et cetera
%d bloggers like this: