Dav*_*nte 18 html css iphone uiwebview
我查看了各种类似的问题和答案,仍然无法使其工作,所以我添加了自己的问题:
我在玩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];
Run Code Online (Sandbox Code Playgroud)
我的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>
Run Code Online (Sandbox Code Playgroud)
我会很感激任何想法或解决方案.非常感谢!
Mat*_*uch 30
将UIWebView的baseURL更改为mainbundle的url.
NSURL *mainBundleURL = [[NSBundle mainBundle] bundleURL];
[self.webView loadHTMLString:htmlString baseURL:mainBundleURL];
Run Code Online (Sandbox Code Playgroud)
斯威夫特3:
webView.loadHTMLString(contentString, baseURL: Bundle.main.bundleURL)
Run Code Online (Sandbox Code Playgroud)
我想我已经弄明白了.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"];
Run Code Online (Sandbox Code Playgroud)
我想我应该发布整个代码块来访问外部 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];
}
Run Code Online (Sandbox Code Playgroud)