記錄一下。css
webview(或wk)用 loadHTMLString加載內容時 ,若是隻是單純的html內容,樣式等都寫在內部,直接設置baseURL爲nil便可。html
不過當html裏包含外部樣式或調用外部js文件時,就須要經過baseurl設置一下路徑。git
[_webView loadHTMLString:html baseURL:myUrl];
舉個最簡單例子:github
<html> <head> <link rel="stylesheet" href="testwai.css"> </head> <body> 123 i'm content! </body> </html>
這裏的html內部,有一個外部css引用,假設這個css文件在項目裏web
咱們能夠實現:app
-(void) loadBundle{ NSMutableString *html = [NSMutableString string]; [html appendString:@"<html><head>"]; [html appendFormat:@"<link rel=\"stylesheet\" href=\"testwai.css\"></head>"]; [html appendString:@"<body><p>qfdkjeakofjadfdsjf</p></body></html>"]; NSURL *myUrl = [NSURL fileURLWithPath:[NSBundle mainBundle].bundlePath]; [_webView loadHTMLString:html baseURL:myUrl]; }
這裏,重點在於這個baseURL參數,因爲在項目裏,因此路徑用 [NSBundle mainBundle].bundlePath 獲取便可。測試
同理若是是沙盒路徑:url
-(void) loadLocal{ NSMutableString *html = [NSMutableString string]; [html appendString:@"<html><head>"]; [html appendFormat:@"<link rel=\"stylesheet\" href=\"testwai.css\"></head>"]; [html appendString:@"<body><p>qfdkjeakofjadfdsjf</p></body></html>"]; NSString *cssUrl = [NSString stringWithFormat:@"%@",NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)]; NSURL *myUrl = [NSURL fileURLWithPath:cssUrl]; [_webView loadHTMLString:html baseURL:myUrl]; }
示例demo下載spa
測試項目裏,點擊下圖這個便可。code