NSAttributedString已在字符串中对抗css脚本

时间:2015-03-05 22:01:43

标签: ios swift nsattributedstring

好的,我遇到了NSAttributeString的问题。我得到了不同的html / css字符串,占用了" busDescriptio"取决于您从网站数据库中选择的业务。我能够自定义我认为合适的字符串作为NSAttributeString但不幸的是在某些情况下字符串已经有css脚本,它覆盖了我插入字符串的样式。是否可以覆盖我的字符串中的脚本?如果是这样,我怎么能这样做? ***如果我无法覆盖脚本,我可以从字符串中提取某个标签或替换它吗?哦,这是我的字符串的样子。如您所见,它们是一种在字符串aka(busDescriptio)中被填充的样式。我无法使用NSAttributeString通过常规脚本更改它。

 /* This is a random description my busDescriptio pulls in which changes everytime someone selects a different business*/<p><span style="color:rgb(0, 0, 0); font-family:verdana,arial,tahoma; font-size:12px">Baxter Eye Care has been serving The Woodlands with quality eye care and personal friendly service since 1981. &nbsp;Dr. Baxter, Dr. Daniels and Dr. Shosa are dedicated to your eye health and vision needs.</span></p>

这是我用来执行此操作的代码

extension String {
    var html2String:String {
        return NSAttributedString(data: dataUsingEncoding(NSUTF8StringEncoding)!, options: [NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType,NSCharacterEncodingDocumentAttribute:NSUTF8StringEncoding], documentAttributes: nil, error: nil)!.string
    }
    var html2NSAttributedString:NSAttributedString {
        return NSAttributedString(data: dataUsingEncoding(NSUTF8StringEncoding)!, options: [NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType,NSCharacterEncodingDocumentAttribute:NSUTF8StringEncoding], documentAttributes: nil, error: nil)!
    }
}
extension NSData{
    var htmlString:String {
        return  NSAttributedString(data: self, options: [NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType,NSCharacterEncodingDocumentAttribute:NSUTF8StringEncoding], documentAttributes: nil, error: nil)!.string
    }
}
let result = html2String("\(busDescriptio)") // Business Description HTML

            let yourAttributedText = "<style type=\"text/css\">#busDescriptio{color:white;align-content:left;}#green{color:#0F0}#blue{color: #00F; font-weight: Bold; font-size: 32}</style><span id=\"busDescriptio\" >\(result),</span><span id=\"green\" > Green </span><span id=\"blue\">and Blue</span>".html2NSAttributedString

            // Create UITextView
            var textView = UITextView(frame: CGRectMake(0, 95.0, screenWidth-10, 300.0))
            textView.attributedText = yourAttributedText
            textView.backgroundColor = UIColor.clearColor()
            textView.font = UIFont.preferredFontForTextStyle(UIFontTextStyleBody)

            border.addSubview(textView)
func html2String(html:String) -> String {
        return NSAttributedString(data: html.dataUsingEncoding(NSUTF8StringEncoding)!, options:[NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType,NSCharacterEncodingDocumentAttribute:NSUTF8StringEncoding], documentAttributes: nil, error: nil)!.string
    }

2 个答案:

答案 0 :(得分:3)

我认为您一直在思考HTML。从HTML中创建NSAttributedString或更准确地说NSMutableAttributedString之后,您就可以应用自己的属性了。那时,HTML已不再相关。你肯定不应该在将HTML转换为属性字符串之前通过操纵HTML来尝试实现格式化。

你不会说什么&#34;风格&#34;或者你想要改变的属性,所以很难给你一个例子,但只需设置或删除你想要的任何属性。您可以完全覆盖HTML中CSS引入的任何样式。

例如,执行[someMutableAttributedString addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(0, someMutableAttributedString.length)]将颜色更改为蓝色。


这是一些适用于OS X的Objective-C代码:

NSString* html = @"<style type=\"text/css\">#busDescriptio{color:white;align-content:left;}#green{color:#0F0}#blue{color: #00F; font-weight: Bold; font-size: 32}</style><span id=\"busDescriptio\" ><p><span style=\"color:rgb(0, 0, 0); font-family:verdana,arial,tahoma; font-size:12px\">Baxter Eye Care has been serving The Woodlands with quality eye care and personal friendly service since 1981. &nbsp;Dr. Baxter, Dr. Daniels and Dr. Shosa are dedicated to your eye health and vision needs.</span></p>,</span><span id=\"green\" > Green </span><span id=\"blue\">and Blue</span>";
NSData* data = [html dataUsingEncoding:NSUTF8StringEncoding];

NSMutableAttributedString* str = [[NSMutableAttributedString alloc] initWithData:data
                                                                         options:@{ NSCharacterEncodingDocumentOption: @(NSUTF8StringEncoding),
                                                                                    NSDocumentTypeDocumentOption: NSHTMLTextDocumentType }
                                                              documentAttributes:NULL
                                                                           error:NULL];
[str addAttribute:NSForegroundColorAttributeName value:[NSColor redColor] range:NSMakeRange(0, str.length)];
self.label.attributedStringValue = str;

我不在Swift工作,但这只是一个简单的翻译:

let html = "<style type=\"text/css\">#busDescriptio{color:white;align-content:left;}#green{color:#0F0}#blue{color: #00F; font-weight: Bold; font-size: 32}</style><span id=\"busDescriptio\" ><p><span style=\"color:rgb(0, 0, 0); font-family:verdana,arial,tahoma; font-size:12px\">Baxter Eye Care has been serving The Woodlands with quality eye care and personal friendly service since 1981. &nbsp;Dr. Baxter, Dr. Daniels and Dr. Shosa are dedicated to your eye health and vision needs.</span></p>,</span><span id=\"green\" > Green </span><span id=\"blue\">and Blue</span>"
let data = html.dataUsingEncoding(NSUTF8StringEncoding)!

var str = NSMutableAttributedString(data:data,
                                    options:[ NSCharacterEncodingDocumentOption: NSUTF8StringEncoding,
                                              NSDocumentTypeDocumentOption: NSHTMLTextDocumentType ],
                                    documentAttributes:nil,
                                    error:nil)
str.addAttribute(NSForegroundColorAttributeName, value:NSColor.redColor(), range:NSMakeRange(0, str.length))
self.label.attributedStringValue = str;

因此,代码以字符串中的HTML代码开头。它从中创建NSMutableAttributedString。然后它会改变前景色,有效地替换HTML产生的颜色。最后,它将属性字符串设置为NSTextField标签的内容。对于iOS,您可以使用UILabelUITextView或其他任何内容。

在你提出的问题代码中,有些事情很麻烦。不清楚busDescription是什么。它是一个包含HTML代码的字符串吗?

您是否有理由将其插入字符串以将其传递给html2String()?那就是为什么:

let result = html2String("\(busDescriptio)")

而不是这个:

let result = html2String(busDescriptio)

似乎html2String()将HTML解释为属性字符串,然后只从中提取纯文本。你为什么这样做?

然后,您将该纯文本插入到另一个HTML代码块中。再说一遍,你为什么这样做?如果要将颜色,字体等应用于纯文本字符串,只需直接从该纯文本字符串构建一个属性字符串 - 不涉及HTML - 并应用所需的属性。

或者,从原始busDescriptio开始,从该HTML代码中创建一个可变的属性字符串,并将您喜欢的任何属性应用于该代码。

例如,这是另一个例子:

NSString* busDescriptio = @"<p><span style=\"color:rgb(0, 0, 0); font-family:verdana,arial,tahoma; font-size:12px\">Baxter Eye Care has been serving The Woodlands with quality eye care and personal friendly service since 1981. &nbsp;Dr. Baxter, Dr. Daniels and Dr. Shosa are dedicated to your eye health and vision needs.</span></p>";
NSData* data = [busDescriptio dataUsingEncoding:NSUTF8StringEncoding];
NSMutableAttributedString* foo = [[NSMutableAttributedString alloc] initWithData:data
                                                                         options:@{ NSCharacterEncodingDocumentOption: @(NSUTF8StringEncoding),
                                                                                    NSDocumentTypeDocumentOption: NSHTMLTextDocumentType }
                                                              documentAttributes:NULL
                                                                           error:NULL];
[str addAttribute:NSFontAttributeName value:[NSFont fontWithName:@"Verdana" size:12] range:NSMakeRange(0, str.length)];

基本上,尽管您的初始输入是HTML代码,但您可以从中构建一个可变的属性字符串,然后从那时起就不能使用HTML。只需根据需要应用和/或删除属性字符串中的属性。您还可以构建单独的属性字符串,例如示例中的绿色或蓝色文本,并将其附加到可变字符串。

答案 1 :(得分:0)

好吧,使用Ken Thomases所写的内容,我能够让它发挥作用!看完他的代码,看看我做错了什么,我就能让它运转起来。这里是Swift代码,万一有人遇到同样的问题。我仍然遇到一些图片有问题,但最理想的是字体颜色,大小,高度,对齐和背景工作!感谢

// busDescriptio is being occupied by a string with html and css scripting
var data: NSData = busDescriptio.dataUsingEncoding(NSUTF8StringEncoding)!
            var foo: NSMutableAttributedString = NSMutableAttributedString(data: data,
                options: [NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType,NSCharacterEncodingDocumentAttribute:NSUTF8StringEncoding],
            documentAttributes:nil,
            error:nil)!
            var paragraph = NSMutableParagraphStyle()
            paragraph.alignment = NSTextAlignment.Left
            foo.addAttribute(NSFontAttributeName, value: UIFont(name: "Arial", size:12)!, range:NSMakeRange(0, foo.length))
            foo.addAttribute(NSForegroundColorAttributeName, value: UIColor.whiteColor(), range: NSRange(location:0,length: foo.length))
            foo.addAttribute(NSBackgroundColorAttributeName, value: UIColor.clearColor(), range: NSRange(location: 0, length: foo.length))
            foo.addAttribute(NSParagraphStyleAttributeName, value:paragraph, range:NSMakeRange(0, foo.length))