gpt4 book ai didi

ios - Swift 3 使用 NSAttributedString 渲染 textview 但想要更改默认字体

转载 作者:行者123 更新时间:2023-11-28 08:01:48 26 4
gpt4 key购买 nike

如果这可以解决,首先要说声谢谢..所以我有 textview 获取带有 html 标签的数据..所以我使用 attributedText 和函数来呈现 html..它有效..但我需要更改font family..现在默认是“times new roman”我想改成“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

它有效,但字体默认变成“times new roman”我需要改变它..有什么想法吗?我以前很感激..谢谢!

enter image description here

我也已经试过了...见下图

enter image description here

最佳答案

您的属性字符串必须如下所示:

使用 this link

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)

关于ios - Swift 3 使用 NSAttributedString 渲染 textview 但想要更改默认字体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46460034/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com