簡體   English   中英

從 HTML 暗模式初始化的 NSAttributedString,如何設置默認前景色?

[英]NSAttributedString initialised from HTML dark mode, how to set default foreground color?

在將現有應用程序轉換為暗模式時,我偶然發現了一個帶有NSAttributedStringUITextView的初始化,以便為某些應用程序商店的法律術語提供細則。 這在淺色模式下看起來不錯,但在深色模式下,我會在黑色上看到黑色文本。 我提供默認前景色的第一個想法是添加以下內容:

import UIKit

let fgColor: UIColor
if #available(iOS 13.0, *) {
    fgColor = .label
} else {
    fgColor = .black
}
let s = try NSAttributedString(data: NSLocalizedString("""
        <p style="text-align: center; font-size: smaller;">
        Your payment will be charged to your iTunes Account at confirmation of purchase. Your subscription automatically renews unless auto-renew is turned off at least 24-hours before the end of the current period. Your Account will be charged for renewal within 24-hours prior to the end of the current period at the same price as the original subscription.
        </p>
        <p style="text-align: center; font-weight: bold; font-size: smaller;">
        <a href="https://www.example.com/tos.html">Terms of Service</a>&nbsp;&vert;&nbsp;<a href="https://www.example.com/policy.html">Privacy Policy</a>
        </p>
""", comment: "legalese").data(using: String.Encoding.utf8, allowLossyConversion: false)!,
                               options: [.documentType: NSAttributedString.DocumentType.html.rawValue,
                                         .defaultAttributes: [NSAttributedString.Key.foregroundColor: fgColor]],
                               documentAttributes: nil)

但無論我嘗試什么,我都無法更改默認的前景色。 有任何想法嗎?

我試圖創建一個擴展。

在這里,數據是我要轉換為屬性字符串的 HTML 數據,“appLabelBlueColor”和“appSystemSecondaryColor”是我想在暗模式下反映的系統 colors。

var htmlToAttributedString: NSAttributedString? {   
guard let data = data(using: .utf16,allowLossyConversion: true)
else { return NSAttributedString() }

 do {
        let attributedString = try NSMutableAttributedString(data: data, options: [NSAttributedString.DocumentReadingOptionKey.documentType:  NSAttributedString.DocumentType.html], documentAttributes: nil)
        attrbutedString.addAttributes([NSAttributedString.Key.font:UIFont.systemFont(ofSize: 10, weight: .light), NSAttributedString.Key.foregroundColor: UIColor(named: "appLabelBlueColor")!, NSAttributedString.Key.backgroundColor: UIColor(named: "appSystemSecondaryColor")!], range: NSRange(
                                            location: 0,
                                            length: attribitedString.length))
        return attributedString

    } catch
    {
        return NSAttributedString()
    }
}

用法:

cell.detailLabel.attributedText = mfPerformanceTableObjectModel[indexPath.section].contentText.htmlToAttributedString

暫無
暫無

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

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