Swift 3使用NSAttributedString渲染textview但要更改默认字体 [英] Swift 3 render textview using NSAttributedString but want change the default font
问题描述
首先要说谢谢,如果这可以解决..so,我有textview可以获取带有html标签的数据..so,我使用attributedText和函数来呈现html ..它起作用了..但是我需要更改字体家族..现在默认情况下它是"times new roman",我想更改为"Helvetica"有什么线索吗?我为此使用扩展名:
First wanna say thank you before if this can be solved..so i have textview that get the data with html tag..so i use attributedText and function to render html..it worked..but i need to change the font family..right now by default it "times new roman" i want to change to "Helvetica" any clue? i use the extension for this :
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
它工作了,但是字体默认变成了"Times new Roman",我需要更改它.之前我非常感谢.谢谢!
it worked but the font default become "times new roman" i need to change it..any idea? i am very appreciate it before..thank you!
我也已经尝试过...请参见下图
I also already try this...see image below
推荐答案
您的属性字符串必须如下所示:
Your attributed string must be like below :
使用此链接
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)
这篇关于Swift 3使用NSAttributedString渲染textview但要更改默认字体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!