Reputation: 1747
I've read many of the existing questions and answers for my problem but none seem to answer it specifically and simply.
I am displaying many HTML files in my app and want to use a CSS to help format them. The CSS file will be held locally together with the HTML files.
I think I want to add the CSS ref inline - presuming that's then right way to do it?
My code is
- (void)viewDidAppear:(BOOL)animated {
[super viewWillAppear:animated];
[adviceContent loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle]
pathForResource:[advice objectForKey:@"HTML"] ofType:@"html"]
isDirectory:NO]]];
[super viewDidAppear:animated];
}
And I've inserted my CSS reference in the HTML file thus within the head tags < link rel="stylesheet" type="text/css" href="photovaluesCSS_2column.css" media="screen"/>
Can someone explain where I'm going wrong? Thanks
Upvotes: 3
Views: 3508
Reputation: 5932
When loading the HTML, you need to specify a base URL for the css file, so your controller will "know" where that CSS file is located.
Here's a code that loads a html string which uses a css file. You can load the entire css from a file, or modify it as you need.
// HTML files are stored in the main bundle
NSBundle *bundle = [NSBundle mainBundle];
NSString *path = [bundle bundlePath];
NSString *filename = @"none";
NSString *fullPath = [NSBundle pathForResource:filename ofType:@"html" inDirectory:path];
// load a HTML from a file
NSString *chapter_filename = [NSString stringWithFormat:@"Section%d", _chapter];
NSString *sectionHTMLPath = [[NSBundle mainBundle] pathForResource:chapter_filename ofType:@"html"];
NSString* htmlContent = [NSString stringWithContentsOfFile:sectionHTMLPath encoding:NSUTF8StringEncoding error:nil];
// add a generic template and the css file directive
NSString* htmlString = @"<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"> <html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"he\" lang=\"he\"><head><style type=\"text/css\" media=\"all\">@import \"styles.css\";</style><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" /></head><body>%@</body></html>";
// load the html into a web view
NSURL *url = [NSURL fileURLWithPath:fullPath];
[_webView loadHTMLString:[NSString stringWithFormat:htmlString, htmlContent] baseURL:url];
Upvotes: 2