Swift 3使用NSAttributedString呈现textview,但要更改默认的字体
首先要说,谢谢你,如果这可以解决..所以我有TextView,获取数据与HTML标记..所以我使用的JavasText和函数来呈现HTML ..它的工作..但我需要改变字体家族。 。现在默认它“时代新罗马”我想改变为“Helvetica”的任何线索? 我使用扩展名为:
extension Data { var attributedString: NSAttributedString? { do { return try NSAttributedString(data: self, options:[NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: String.Encoding.utf8.rawValue], documentAttributes: nil) } catch { print(error) } return nil }} extension String { var data: Data { return Data(utf8) }}
然后我用它:
cell.txtview.attributedText = contentText.data.attributedString
它的工作,但字体默认为“时代新罗马”我需要改变它..任何想法? 我非常感激之前..谢谢你!
在这里input图像描述
我也已经试过这个…看下面的图片
在这里input图像描述
您的属性string必须如下所示:
使用此链接
let data = "vini".data(using: .utf8) let attributedString = data!.attributedString let newAttributedString = NSMutableAttributedString(attributedString: (attributedString)!) newAttributedString.enumerateAttribute(NSFontAttributeName, in: NSMakeRange(0, (newAttributedString.length)), options: []) { value, range, stop in guard let currentFont = value as? UIFont else { return } let fontDescriptor = currentFont.fontDescriptor.addingAttributes([UIFontDescriptorFamilyAttribute: "Helvetica"]) if let newFontDescriptor = fontDescriptor.matchingFontDescriptors(withMandatoryKeys: [UIFontDescriptorFamilyAttribute]).first { let newFont = UIFont(descriptor: newFontDescriptor, size: currentFont.pointSize) newAttributedString.addAttributes([NSFontAttributeName: newFont], range: range) } } print(newAttributedString)