Swift 3 render textview using NSAttributedString b

2019-07-31 07:26发布

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条回答
放我归山
2楼-- · 2019-07-31 07:46

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)
查看更多
登录 后发表回答