首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在Xcode中将外部样式表添加到UIWebView?

如何在Xcode中将外部样式表添加到UIWebView?
EN

Stack Overflow用户
提问于 2011-02-20 03:47:14
回答 3查看 19.3K关注 0票数 18

我已经看了各种类似的问题和答案,但仍然不能让它工作,所以我添加了我自己的问题:

我在和UIWebView玩。我可以创建一个具有内联CSS的工作html页面。如果CSS在app资源组的文件中,我不知道如何加载它。

我的代码是:

代码语言:javascript
复制
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调用是这样的:

代码语言:javascript
复制
<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>

如果有任何想法或解决方案,我将不胜感激。非常感谢!

EN

回答 3

Stack Overflow用户

发布于 2011-08-19 11:23:11

我想我已经弄明白了。htmlString只是一个NSString,我们可以替换其中的文本。这段代码对我很有效

代码语言:javascript
复制
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"];
票数 8
EN

Stack Overflow用户

发布于 2011-02-20 18:15:10

我想我应该发布整个代码块来访问外部CSS文件。希望它能对其他人有用:

代码语言:javascript
复制
- (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
EN

Stack Overflow用户

发布于 2011-08-04 21:39:58

代码语言:javascript
复制
NSURL *BundleURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"name your style" ofType:@"css"]];
webView.opaque = NO;
webView.backgroundColor=[UIColor clearColor];
[webView loadHTMLString:htmlString baseURL:BundleURL];
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5053109

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档