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

本秂侑毒 提交于 2019-11-28 20:33:01
Matthias Bauch

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)
Eldhose

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"];

I thought I should post the entire code block to access an external CSS file. Hopefully, it will be useful to others:

- (void)viewDidLoad
{
    NSURL *mainBundleURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]];

    NSString *path = [[NSBundle mainBundle] pathForResource:@"mypagename" 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:mainBundleURL];

    [htmlString release];
}
NSURL *BundleURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"name your style" ofType:@"css"]];
webView.opaque = NO;
webView.backgroundColor=[UIColor clearColor];
[webView loadHTMLString:htmlString baseURL:BundleURL];
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!