我使用NSAttributedString或UIWebView Swift

我得到不同的string占据“busDescriptio”取决于您从网站数据库中select的业务。 该string包含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) 

我不喜欢这是如何工作,所以这就是我想要做的。 – 我想改变字体大小,字体颜色,并采取与我的string(busDescriptio)的图像。 我使用UIWebView来完成这个或NSAttributedString? 如果是这样,我该怎么做?

 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 

属性string是一个带有属性的string。

string属性返回没有属性的string。

你正在build立一个属性的string,扔掉所有的属性,然后把文本交给文本视图。

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