簡體   English   中英

Swift 3使用NSAttributedString渲染textview但要更改默認字體

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

首先要說謝謝,如果這可以解決..so,我有textview可以獲取帶有html標簽的數據..so,我使用attributedText和函數來呈現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”,我需要更改它。 我之前非常感謝..謝謝!

在此處輸入圖片說明

我也已經嘗試過...參見下圖

在此處輸入圖片說明

您的屬性字符串必須如下所示:

使用此鏈接

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM