我得到了不同的字符串,占用了" 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?如果是这样我怎么能这样做?
答案 0 :(得分:3)
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
答案 1 :(得分:1)
属性字符串是具有属性的字符串。
string
属性返回没有属性的字符串。
您正在构建一个包含属性的字符串,丢弃所有属性,然后只将文本处理到文本视图。
将attributedString
设置为文本视图的attributedText
属性,为其提供属性。