Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add an external stylesheet to a UIWebView in Xcode?

I have looked at various similar questions and answers and still cannot get this to work, so I'm adding my own question:

I'm playing with UIWebView. I can create a working html page with inline CSS. I cannot figure out how to get the CSS to load if it is in a file in the app resources group.

My code is:

NSString *path = [[NSBundle mainBundle] pathForResource:@"webViewPage2" ofType:@"html"];
    NSFileHandle *readHandle = [NSFileHandle fileHandleForReadingAtPath:path];

    NSString *htmlString = [[NSString alloc] initWithData: 
                              [readHandle readDataToEndOfFile] encoding:NSUTF8StringEncoding];


    webView.opaque = NO;
    webView.backgroundColor = [UIColor clearColor];
    [self.webView loadHTMLString:htmlString baseURL:nil];
    [htmlString release];

And my html call is this:

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-scalable=no, width=device-width">
<link rel="stylesheet" type="text/css" media="only screen and (max-device-width: 480px)" href="/greek123.css" />
</head>

<body style="background-color: transparent;">

<h2>Some Title</h2>


<p>We can put instructions here. Such as: 
"uh-oh You should not have pushed that button!"
</p>


</body>

</html>

I would appreciate any ideas or solutions. Many thanks!

like image 964
ICL1901 Avatar asked Feb 19 '11 19:02

ICL1901


2 Answers

change the baseURL of the UIWebView to the url of your mainbundle.

NSURL *mainBundleURL = [[NSBundle mainBundle] bundleURL];
[self.webView loadHTMLString:htmlString baseURL:mainBundleURL];

Swift 3:

webView.loadHTMLString(contentString, baseURL: Bundle.main.bundleURL)
like image 101
Matthias Bauch Avatar answered Oct 11 '22 14:10

Matthias Bauch


I think i have figured it out. the htmlString is simply an NSString we can replace text in it. this code worked for me

NSString *info = [NSString stringWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"your html file name" ofType:@"html"] encoding: NSUTF8StringEncoding error: &error];

info=[info stringByReplacingOccurrencesOfString:@"styles.css" withString:@"stylesIPad.css"];
like image 24
Eldhose Avatar answered Oct 11 '22 12:10

Eldhose