Ios7 如何将CSS for HTML添加到NSAttributedString?
我试图通过加载一个HTML文件,以在一个窗口中显示它Ios7 如何将CSS for HTML添加到NSAttributedString?,ios7,uitextview,nsattributedstring,Ios7,Uitextview,Nsattributedstring,我试图通过加载一个HTML文件,以在一个窗口中显示它 那么,如何将CSS应用于文本视图的内容呢?由于iOS 7,您可以使用HTML语法使用NSAttributeString: NSURL *htmlString = [[NSBundle mainBundle] URLForResource: @"string" withExtension:@"html"]; NSAttributedString *stringWithHTMLAttributes = [[NSAttributedStr
那么,如何将CSS应用于文本视图的内容呢?由于iOS 7,您可以使用HTML语法使用
NSAttributeString
:
NSURL *htmlString = [[NSBundle mainBundle] URLForResource: @"string" withExtension:@"html"];
NSAttributedString *stringWithHTMLAttributes = [[NSAttributedString alloc] initWithFileURL:htmlString
options:@{NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType}
documentAttributes:nil
error:nil];
textView.attributedText = stringWithHTMLAttributes; // attributedText field!
您必须将string.html添加到项目中,html的内容可以如下所示:
<html>
<head>
<style type="text/css">
body {
font-size: 15px;
font-family: Avenir, Arial, sans-serif;
color: red;
}
</style>
</head>
<body>
<p>This is the text</p>
</body>
</html>
身体{
字体大小:15px;
字体系列:Avenir、Arial、无衬线;
颜色:红色;
}
这是文本
根据我的测试,您可以更改:颜色、字体系列、字体重量、字体大小、文本对齐,并使用
、
、
、
、
和
标记。而不是在多个文件中重复所需的css,如果您将文件存储在资产文件夹中,那么一个选项是在body标记之前有一个包含所有html的文件,body标记包含所有样式信息。然后可以从我自己的代码中附加字节,如本例所示:
func loadHTMLData(section:String, page:Int) -> NSAttributedString? {
var data = Data()
if let asset = NSDataAsset(name: "htmlhead") {
data.append(asset.data)
}
if let asset = NSDataAsset(name: "\(section)\(page)") {
data.append(asset.data)
do {
let attr = try NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html], documentAttributes: nil)
return attr
}
catch {
// do something with error
return nil
}
}
else {
return nil
}
}
如果您愿意,也没有什么可以阻止您进一步拆分文件。我想您不能将css应用于textview,而应该使用html文件在webview中显示内容。@Virussmca但我必须使用textview@谢谢你的编辑。你不能应用所有的CSS属性(比如左边框:10px solid#000000;等等)@AndréRodrigues你知道我在哪里可以找到可能的定制列表吗?我正在尝试为列表(