簡體   English   中英

swift中解析Html時strong tag出現問題 5

[英]Problem in strong tag when Parsing Html in swift 5

您好我在將 Html 解析為 UILabel 中的 NSAtributtedString 時遇到問題。 問題出在強文本中,結果太粗了(我猜當解析字體時更改為“GibsonBold”,我需要 GibsonSemibold,甚至從 Regular 更改為 Medium。我嘗試將標簽更改為 < b > 或實現一個風格,但結果總是一樣的。我也嘗試了幾個擴展,但結果都是一樣的。

這是 html 字符串:

"<p>First text <strong> this text should be at lest Semibold</strong>. Final text.</p>"

我使用這兩個擴展來解析:

extension UIColor {
    var hexString:String? {
        if let components = self.cgColor.components {
            let r = components[0]
            let g = components[1]
            let b = components[2]
            return  String(format: "%02X%02X%02X", (Int)(r * 255), (Int)(g * 255), (Int)(b * 255))
        }
        return nil
    }
}

extension String {
    var html2Attributed: NSAttributedString? {
        do {
            guard let data = data(using: String.Encoding.utf8) else {
                return nil
            }
            return try NSAttributedString(data: data,
                                          options: [.documentType: NSAttributedString.DocumentType.html,
                                                    .characterEncoding: String.Encoding.utf8.rawValue],
                                          documentAttributes: nil)
        } catch {
            print("error: ", error)
            return nil
        }
    }
    
    var htmlAttributed: (NSAttributedString?, NSDictionary?) {
        do {
            guard let data = data(using: String.Encoding.utf8) else {
                return (nil, nil)
            }

            var dict:NSDictionary?
            dict = NSMutableDictionary()

            return try (NSAttributedString(data: data,
                                          options: [.documentType: NSAttributedString.DocumentType.html,
                                                    .characterEncoding: String.Encoding.utf8.rawValue],
                                          documentAttributes: &dict), dict)
        } catch {
            print("error: ", error)
            return (nil, nil)
        }
    }
    
    func htmlAttributed(using font: UIFont, color: UIColor, lineHeight: CGFloat) -> NSAttributedString? {
        do {
            let htmlCSSString = "<style>" +
                "html *" +
                "{" +
                "font-size: \(font.pointSize * 0.75)pt !important;" +
                "color: #\(color.hexString!) !important;" +
                "font-family: \(font.familyName), Helvetica !important;" +
                "line-height: \(lineHeight * 0.06) !important;" +
                "}</style> \(self)"

            guard let data = htmlCSSString.data(using: String.Encoding.utf8) else {
                return nil
            }

            return try NSAttributedString(data: data,
                                          options: [.documentType: NSAttributedString.DocumentType.html,
                                                    .characterEncoding: String.Encoding.utf8.rawValue],
                                          documentAttributes: nil)
        } catch {
            print("error: ", error)
            return nil
        }
    }
}

以及 label 中的實現:

descriptionLabelText.attributedText = description.htmlAttributed(using: UIFont.gibsonRegular.withAdjustedSize(16),
                                                                    color: .greyscale800,
                                                                    lineHeight: 20.adjusted)

目前所有 css 樣式僅定義要使用的字體和字體大小,而不是真正的style (粗體、斜體、常規等)或weights (正常、粗體、淺色等),因此這些標簽采用標簽的默認 styles .

我創建了以下 HTML

let htmlString
            = "<p>Normal text <strong> Strong set to 600 font weight </strong>. <b> Bold set to italic style </b>"

然后我像這樣使用你的代碼

label.attributedText = htmlString.htmlAttributed(using: UIFont(name: "Gibson-Regular",
                                                               size: 16)!,
                                                 color: .red,
                                                 lineHeight: 20)

這給了我你現在可能看到的以下結果

HTML 文本 iOS Swift html 屬性文本標簽自定義樣式和字體

如果您將所有 fonts(Gibson 常規、粗體、斜體)正確添加到您的文件系統中,您可以在 CSS 中添加特定的 styles。

對您的func htmlAttributed的小改動

func htmlAttributed(using font: UIFont,
                    color: UIColor,
                    lineHeight: CGFloat) -> NSAttributedString? {
    do {
        let htmlCSSString = "<style>" +
            "html *" +
            "{" +
            "font-size: \(font.pointSize * 0.75)pt !important;" +
            "color: #\(color.hexString!) !important;" +
            "font-family: \(font.familyName), Helvetica !important;" +
            "line-height: \(lineHeight * 0.06) !important;" +
            "}" +
            
            // customize bold
            "b" +
            "{" +
            "font-size: \(font.pointSize * 0.75)pt !important;" +
            "font-style: italic;" + // I set bold to be italic
            "font-family: \(font.familyName), Helvetica !important;" +
            "line-height: \(lineHeight * 0.06) !important;" +
            "}" +
            
            // customize strong font weight
            // https://developer.mozilla.org/en-US/docs/Web/CSS/font-weight
            "strong" +
            "{" +
            "font-size: \(font.pointSize * 0.75)pt !important;" +
            "font-weight: 600;" + // customize weight to what you want
            "font-family: \(font.familyName), Helvetica !important;" +
            "line-height: \(lineHeight * 0.06) !important;" +
            "}" +
            
            "}</style> \(self)"
        
        guard let data = htmlCSSString.data(using: String.Encoding.utf8) else {
            return nil
        }
        
        return try NSAttributedString(data: data,
                                      options: [.documentType: NSAttributedString.DocumentType.html,
                                                .characterEncoding: String.Encoding.utf8.rawValue],
                                      documentAttributes: nil)
    } catch {
        print("error: ", error)
        return nil
    }
}

通過此更改,您將看到strong標簽的權重發生了一些變化,我將b標簽呈現為斜體

HTML attributed UILabel set font font size font style strong tag bold tag swift iOS

最后,據我所知,您不能將粗細設置為Semi Bold ,因此如果您想使用Semi Bold字體,您已明確將其設置為您要使用的字體。

所以你可以自定義強標簽:

// I set font family to Gibson italic for example
// You can set it to semi bold font
"strong" +
"{" +
"font-size: \(font.pointSize * 0.75)pt !important;" +
"font-family: \(UIFont(name: "Gibson-Italic", size: 16)!), Helvetica !important;" +
"line-height: \(lineHeight * 0.06) !important;" +
"}" +

UILabel 自定義樣式中的 NSAtributtedString 的 Html 粗體 iOS swift

我認為這應該給你一些關於如何定制以適合你的解決方案的想法

暫無
暫無

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

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