GeekedOut
GeekedOut

Reputation: 17185

ios - can't get css file styles to render in HTML from a UIWebView

If I create inline styles they render, but when try to reference a css file in the same group and directory within xCode, they do not render.

Here is what I do:

<html>
<head>
    <link href="main.css" rel="stylesheet" type="text/css" /> 
</head>

<body>

    <h1>Hello, world! Learn</h1>

    <p>
    <a href="myscheme://advertising" class="buttonStyle">Click me!</a>
    </p> 
</body>
</html>

and then I have the css file called main.css like this:

body {background-color:#b0c4de;}
p {background-color:#e0ffff;}

Would anyone know why this would not render the css? Am I missing something important from the HTML header?

Here is how I call the HTML in the first place:

- (void)viewDidAppear:(BOOL)animated
{  
    NSString *htmlFile = [[NSBundle mainBundle] pathForResource:@"learn" 
                                                         ofType:@"html"];

    NSString* htmlString = [NSString stringWithContentsOfFile:htmlFile encoding:NSUTF8StringEncoding error:nil];
    [theWebView loadHTMLString:htmlString baseURL:nil];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:htmlFile]];

    [theWebView loadRequest:request];
}

Upvotes: 2

Views: 2454

Answers (1)

user529758
user529758

Reputation:

The problem is in

[theWebView loadHTMLString:htmlString baseURL:nil];

Since baseURL is nil, the web view has no way to determine where your css file is. Instead of messing with manually creating data and loading it, pass the path of the HTML file directly to the UIWebView:

NSString *htmlFile = [[NSBundle mainBundle] pathForResource:@"learn" ofType:@"html"];
NSURL *url = [NSURL fileURLWithPath:htmlFile];
NSURLRequest *rq = [NSURLRequest requestWithURL:url];
[webView loadRequest:rq];

Upvotes: 8

Related Questions