Как добавить внешнюю таблицу стилей в UIWebView в Xcode?
Я рассмотрел различные подобные вопросы и ответы и до сих пор не могу заставить это работать, поэтому я добавляю свой собственный вопрос:
Я играю с UIWebView. Я могу создать рабочую html-страницу с встроенным CSS. Я не могу понять, как загрузить 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>
Буду признателен за любые идеи или решения. Большое спасибо!
Ответы
Ответ 1
измените baseURL UIWebView на url вашего mainbundle.
NSURL *mainBundleURL = [[NSBundle mainBundle] bundleURL];
[self.webView loadHTMLString:htmlString baseURL:mainBundleURL];
Swift 3:
webView.loadHTMLString(contentString, baseURL: Bundle.main.bundleURL)
Ответ 2
Я думаю, что понял это. 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"];
Ответ 3
Я думал, что должен опубликовать весь блок кода для доступа к внешнему файлу 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];
}
Ответ 4
NSURL *BundleURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"name your style" ofType:@"css"]];
webView.opaque = NO;
webView.backgroundColor=[UIColor clearColor];
[webView loadHTMLString:htmlString baseURL:BundleURL];