Michel
Michel

Reputation: 11755

How to use css with UIWebView?

In my class derived from UIViewController I have a class variable of type UIWebView* called helpView. And I use the following code for viewDidLoad.

- (void)viewDidLoad {
    [super viewDidLoad];
    NSURL *helpFileURL=[NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/tutorial.html",
                                               [[NSBundle mainBundle] resourcePath]]];
    NSURLRequest *request = [NSURLRequest requestWithURL:helpFileURL];
    [helpView loadRequest:request];
}

and things work fine, I can see "tutorial.html" on my simulator and device.

Now here is my question, I want to use a CSS file called tutorial.css along with my tutorial.html. In the same way tutorial.html is in the app bundle, tutorial.css is also in the app bundle.

How should I modify the code above for this to work? I tried a few things on my own, but failed. And I did not find anything clear answer looking on the web. Obviously if I use the usual:

  <link href="css/tutorial.css" rel="stylesheet" type="text/css" />

in my tutorial.html file it is not enough.

Thanks for any information.

Upvotes: 0

Views: 1608

Answers (1)

Tieme
Tieme

Reputation: 65479

Leave out the css directory, your bundle doesn't work that way.

<link href="tutorial.css" rel="stylesheet" type="text/css" />

Then change your code to load the html with a nice base url:

- (void)viewDidLoad {
    [super viewDidLoad];

    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"tutorial" ofType:@"html"];
    NSString *htmlString = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];

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

    [webView loadHTMLString:htmlString baseURL:baseURL];
}

Upvotes: 2

Related Questions