【问题标题】:Swift 3 render textview using NSAttributedString but want change the default fontSwift 3 使用 NSAttributedString 渲染 textview 但想要更改默认字体
【发布时间】:2017-09-28 02:28:14
【问题描述】:

首先想说谢谢你,如果这可以解决..所以我有 textview 用 html 标签获取数据..所以我使用属性文本和函数来呈现 html..它工作..但我需要改变字体系列..现在默认情况下它是“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

【问题讨论】:

    标签: ios iphone swift mobile swift3


    【解决方案1】:

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

    使用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)
    

    【讨论】:

    • 仍然没有工作..我已经尝试过了..我想应该循环内容然后替换它..我找不到那个方法..呃..谢谢!跨度>
    • 更新了答案。请检查。
    • 就是这样..嘿嘿...我也找到了那个答案..它有效..对不起,我只想输入,你已经回答了..非常感谢@Vini App您的所有帮助和支持!太棒了!
    猜你喜欢
    • 1970-01-01
    • 2023-03-09
    • 1970-01-01
    • 2023-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多