簡體   English   中英

更改 NSAttributedString 的字體大小和字體顏色

[英]Changing the fontsize and font color of the NSAttributedString

如何快速更改 NSAttributedString 的字體大小和字體顏色?

 @IBOutlet weak var detailsTextView: UITextView!

 if let data = htmltext.data(using: String.Encoding.utf8, allowLossyConversion: true)
 {
        do
        {
            let newFont =  UIFont(name: "Georgia", size: 22.0) ?? UIFont()    
            let attributedText = try NSAttributedString(data: data, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil)            
            detailsTextView.attributedText = attributedText
        }
        catch{}
}

htmltext 是需要設置為 UILabel 的 html 值

這就是你的做法:

var attributedString = try? NSAttributedString(data: inst.desc.data(using: String.Encoding.unicode), options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil)
var newString = NSMutableAttributedString(attributedString: attributedString!)
var range: NSRange = [0, newString.length]
newString.enumerateAttribute(NSFontAttributeName, in: range, options: .longestEffectiveRangeNotRequired, using: {(_ value: Any, _ range: NSRange, _ stop: Bool) -> Void in
    var replacementFont = UIFont(name: "Palatino-Roman", size: 14.0)
    newString.addAttribute(NSFontAttributeName, value: replacementFont!, range: range)
})
label.attributedText = newString

這是設置 NSAttributedString 屬性的方式:

let attributes: [String : Any] = [NSFontAttributeName: UIFont.systemFont(ofSize: UIFont.systemFontSize, weight: UIFontWeightThin),
    NSForegroundColorAttributeName: UIColor.blue]

let attributedText = NSAttributedString(string: "Some string", attributes: attributes)

用這個

let newAttributedString = NSMutableAttributedString(attributedString: label.attributedText)

// Enumerate through all the font ranges
newAttributedString.enumerateAttribute(NSFontAttributeName, in: NSMakeRange(0, 
newAttributedString.length), options: []) { value, range, stop in
guard let currentFont = value as? UIFont else {
    return
}

// An NSFontDescriptor describes the attributes of a font: family name, face name, point size, etc.
// Here we describe the replacement font as coming from the "Hoefler Text" family
let fontDescriptor = currentFont.fontDescriptor.addingAttributes([UIFontDescriptorFamilyAttribute: "Hoefler Text"])

// Ask the OS for an actual font that most closely matches the description above
if let newFontDescriptor = fontDescriptor.matchingFontDescriptors(withMandatoryKeys: [UIFontDescriptorFamilyAttribute]).first {
    let newFont = UIFont(descriptor: newFontDescriptor, size: currentFont.pointSize)
    newAttributedString.addAttributes([NSFontAttributeName: newFont], range: range)
}
label.attributedText = newAttributedString
 }

在此處輸入圖片說明

斯威夫特 5.2

String擴展中添加以下屬性:

extension String
{
    var htmlToAttributedString: NSAttributedString?
    {
        guard let data = data(using: .utf8) else { return nil }
        do
        {
            let paragraphStyle = NSMutableParagraphStyle()
            paragraphStyle.alignment = .right

            let content = try NSMutableAttributedString(data: data, options: [.documentType:     NSAttributedString.DocumentType.html, .characterEncoding:     String.Encoding.utf8.rawValue], documentAttributes: nil)

            content.addAttributes([NSAttributedString.Key.paragraphStyle: paragraphStyle,
                                   NSAttributedString.Key.font: UIFont.alJazeera(.regular(20)),
                                   NSAttributedString.Key.foregroundColor: UIColor.appDark],
                                  range: NSMakeRange(0, content.length))

            return content
        }
        catch
        {
            return nil
        }
    }
}

然后輕松使用它:

textView.attributedText = myText.htmlToAttributedString

注意: UIFont.alJazeera(.regular(20))UIFont擴展中定義的靜態方法, UIColor.appDark也是UIColor擴展中定義的靜態屬性

斯威夫特 3.0

你可以試試這個方法

let finaltext = "<span style='font-family:Georgia; font-size: 20px'>\(Your html string)</span>"
detailsTextView.attributedText = finaltext.html2AttributedString

並添加擴展

extension String {
    var html2AttributedString: NSAttributedString? {
        do {
            return try NSAttributedString(data: Data(utf8), options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: String.Encoding.utf8.rawValue], documentAttributes: nil)
        } catch {
            print(error)
            return nil
        }
    }
 }

暫無
暫無

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

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