Swift 3 render textview using NSAttributedString but want change the default font

女生的网名这么多〃 提交于 2019-12-24 12:17:49

问题


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)
}}

then i use it with :

cell.txtview.attributedText = contentText.data.attributedString

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!

enter image description here

I also already try this...see image below

enter image description here


回答1:


Your attributed string must be like below :

using 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)


来源:https://stackoverflow.com/questions/46460034/swift-3-render-textview-using-nsattributedstring-but-want-change-the-default-fon

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!