Ios Swift 3使用NSAttributedString呈现文本视图,但希望更改默认字体
首先要说声谢谢,如果这个问题能解决的话。所以我有textview,它可以用html标记获取数据。所以我使用attributedText和函数来呈现html。它工作了。但是我需要更改字体系列。现在默认为“times new roman”,我想更改为“Helvetica”,有什么线索吗?我为此使用扩展名:Ios Swift 3使用NSAttributedString呈现文本视图,但希望更改默认字体,ios,iphone,swift,mobile,swift3,Ios,Iphone,Swift,Mobile,Swift3,首先要说声谢谢,如果这个问题能解决的话。所以我有textview,它可以用html标记获取数据。所以我使用attributedText和函数来呈现html。它工作了。但是我需要更改字体系列。现在默认为“times new roman”,我想更改为“Helvetica”,有什么线索吗?我为此使用扩展名: extension Data { var attributedString: NSAttributedString? { do { return try NSAttribu
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”,我需要更改它。有什么想法吗?我以前很感激……谢谢
我也已经试过了…见下图
您的属性字符串必须如下所示: 使用
您的属性字符串必须如下所示: 使用
仍然不起作用..我已经试过了..我想应该循环内容然后替换..我找不到方法..啊..谢谢!更新了答案。请检查。就是这样。嘿嘿…我也找到了答案。而且它也起作用了。很抱歉,我只想键入,你已经回答了。非常感谢@Vini App对你的帮助和支持!太好了!仍然不起作用..我已经试过了..我想应该循环内容然后替换..我找不到方法..啊..谢谢!更新了答案。请检查。就是这样。嘿嘿…我也找到了答案。而且它也起作用了。很抱歉,我只想键入,你已经回答了。非常感谢@Vini App对你的帮助和支持!太好了!
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)