Objective C study note

Apply CSS into your UIWebVIew

First, you need to drag your .css file into your Xcode workspace, I dragged it into the “Supporting Files/”

Then, all you need is these three lines:

NSString *path = [[NSBundle mainBundle] resourcePath];
NSURL *baseURL = [NSURL fileURLWithPath:path];
[webView loadHTMLString:htmlString baseURL:baseURL];

If you’re curious, you can actually log out everything you have in the resourcePath of your App.

    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSArray *dirContents = [fileManager contentsOfDirectoryAtPath:path error:nil];
    NSLog(@"Contents = %@",dirContents);

If you can see your *.css file, you are good to go!

Of course, you would need to add a line of CSS code into the header of your html string to make it aware of that CSS file.

NSMutableString *finalHtmlString = [[NSMutableString alloc]initWithString:@"<link href=\"mobile.css\" rel=\"stylesheet\" type=\"text/css\">"];
[finalHtmlString appendString:htmlString];

BeforeAfter
Before                                                                 After

Advertisements

One thought on “Apply CSS into your UIWebVIew

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

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

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s