WebView即时加载css

ADA*_*DAM 7 webkit objective-c webview

我有以下代码加载和html文件到webview

- (void)awakeFromNib{

    NSString *resourcesPath = [[NSBundle mainBundle] resourcePath];
    NSString *htmlPath = [resourcesPath stringByAppendingString:@"/main.html"];
    [[self mainFrame] loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:htmlPath]]];

}
Run Code Online (Sandbox Code Playgroud)

我将如何动态加载css文件(以最有效的方式),因为它不适合在html文件中使用css文件链接

Rob*_*ger 13

你应该使用Objective-C的DOM API访问DOM,并插入相应的<link><style>元素到DOM.

DOMDocument* domDocument=[webView mainFrameDocument];
DOMElement* styleElement=[domDocument createElement:@"style"];
[styleElement setAttribute:@"type" value:@"text/css"];
DOMText* cssText=[domDocument createTextNode:@"body{font-weight:bold;}"];
[styleElement appendChild:cssText];
DOMElement* headElement=(DOMElement*)[[domDocument getElementsByTagName:@"head"] item:0];
[headElement appendChild:styleElement];
Run Code Online (Sandbox Code Playgroud)