ios - NSAttributedString 与已经在字符串中的 css 脚本作斗争

标签 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
    }

最佳答案

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

你没有说你想改变什么“风格”或属性,所以很难给你一个例子,但只是设置或删除你想要的任何属性。您可以完全覆盖 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 中工作了。只需根据需要从属性字符串中应用和/或删除属性。您还可以构建单独的属性字符串,例如示例中的绿色或蓝色文本,并将它们附加到可变字符串。

关于ios - NSAttributedString 与已经在字符串中的 css 脚本作斗争,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28888613/

相关文章:

ios - 交叉滚动 : tableview inside UIpageViewcontroller does not behave properly

ios - 使用适用于 iOS 的 Google Maps SDK 后应用程序大小增加

ios - uitableview 数据在快速滚动时重复

ios - 在没有 CAKeyframeAnimation 的情况下为沿着路径的 View 设置动画

swift - NSAttributedString,整体更改字体但保留所有其他属性?

ios - 绘制 PDF 时的 CFAttributedString

ios - 安全性-后台事件应用程序-是否存储当前屏幕的图像

ios - NSJSONSerialization JSON 解析问题

json - swift 3 |可选类型的 JSON 值 '[String : Any] not unwrapped, did mean to use ' !' or ' ?'?

ios - 具有多个链接的 UILabel