我查看了各种类似的问题和答案,仍然无法使其发挥作用,所以我正在添加自己的问题:
我正在玩UIWebView。我可以使用内联CSS创建一个工作的html页面。如果它位于应用资源组的文件中,我无法弄清楚如何加载CSS。
我的代码是:
NSString *path = [[NSBundle mainBundle] pathForResource:@"webViewPage2" 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:nil];
[htmlString release];
我的html电话是这样的:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-scalable=no, width=device-width">
<link rel="stylesheet" type="text/css" media="only screen and (max-device-width: 480px)" href="/greek123.css" />
</head>
<body style="background-color: transparent;">
<h2>Some Title</h2>
<p>We can put instructions here. Such as:
"uh-oh You should not have pushed that button!"
</p>
</body>
</html>
我会很感激任何想法或解决方案。非常感谢!
答案 0 :(得分:30)
将UIWebView的baseURL更改为mainbundle的url。
NSURL *mainBundleURL = [[NSBundle mainBundle] bundleURL];
[self.webView loadHTMLString:htmlString baseURL:mainBundleURL];
斯威夫特3:
webView.loadHTMLString(contentString, baseURL: Bundle.main.bundleURL)
答案 1 :(得分:8)
我想我已经弄明白了。 htmlString只是一个NSString,我们可以替换它中的文本。这段代码对我有用
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"];
答案 2 :(得分:4)
我以为我应该发布整个代码块来访问外部CSS文件。希望它对其他人有用:
- (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];
}
答案 3 :(得分:2)
NSURL *BundleURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"name your style" ofType:@"css"]];
webView.opaque = NO;
webView.backgroundColor=[UIColor clearColor];
[webView loadHTMLString:htmlString baseURL:BundleURL];