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

前端 未结 4 1802

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

相关标签:
4条回答
  • 2020-12-14 09:30

    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)
    
    0 讨论(0)
  • 2020-12-14 09:36

    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];
    }
    
    0 讨论(0)
  • 2020-12-14 09:39
    NSURL *BundleURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"name your style" ofType:@"css"]];
    webView.opaque = NO;
    webView.backgroundColor=[UIColor clearColor];
    [webView loadHTMLString:htmlString baseURL:BundleURL];
    
    0 讨论(0)
  • 2020-12-14 09:45

    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"];
    
    0 讨论(0)
提交回复
热议问题