我使用 NSAttributedString 还是 UIWebView Swift

Do I use NSAttributedString or UIWebView Swift

根据您从网站数据库中选择的业务,我得到了占用 "busDescriptio" 的不同字符串。此字符串包含 html 个标签、图像和链接。我被告知使用 NSAttributedString 而不是 UIWebView,因为 UIWebView 给我带来了各种各样的问题,例如图像位置错误、文本字体和文本颜色无法完全正常工作。我是 Swift 的新手,所以我无法真正了解 NSAttributedString 的工作原理。我能够去掉 html 标签并保留字体,但这会带走图像、链接和分机。有了这个

let encodedString = "\(busDescriptio)"
            let encodedData = encodedString.dataUsingEncoding(NSUTF8StringEncoding)!
            let attributedOptions = [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType]
            let attributedString = NSAttributedString(data: encodedData, options: attributedOptions, documentAttributes: nil, error: nil)

            let decodedString = attributedString?.string 

然后我将它加载到 UITextView

// Create UITextView
            var textView = UITextView(frame: CGRectMake(0, 95.0, screenWidth-10, 300.0))
            textView.text = decodedString
            textView.font = UIFont.preferredFontForTextStyle(UIFontTextStyleBody)

            border.addSubview(textView)

我不喜欢它的工作原理,所以这就是我想要做的。 - 我想更改字体大小、字体颜色,并使用我的字符串 (busDescriptio) 获取图像。我是使用 UIWebView 还是使用 NSAttributedString 来完成这项工作?如果可以,我该怎么做?

属性字符串是具有属性的字符串。

string 属性 returns 没有属性的字符串。

您正在构建一个带有属性的字符串,丢弃所有属性,然后仅将文本传递给文本视图。

attributedString 设置为文本视图的 attributedText 属性 以赋予其属性。

extension String {
    var html2AttStr:NSAttributedString {
        return NSAttributedString(data: dataUsingEncoding(NSUTF8StringEncoding)!, options:[NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: NSUTF8StringEncoding], documentAttributes: nil, error: nil)!
    }
}

let yourAttributedText = "<style type=\"text/css\">#red{color:#F00}#green{color:#0F0}#blue{color: #00F; font-weight: Bold; font-size: 32}</style><span id=\"red\" >Red,</span><span id=\"green\" > Green </span><span id=\"blue\">and Blue</span>".html2AttStr

textView.attributedText = yourAttributedText