简体   繁体   中英

HTML attributed string in Swift iOS

I have an HTML text coming from the API and I wanted to show that in a UILabel using Swift.

Play million of songs ad-free across all your devices.* Terms and conditions applied.<br><br><small>* Requires a subscription</small>

This string coming from API is of Times New Roman font. But, I want this whole string to be in a custom font with size 20, and the text under <small>* Requires a subscription</small> to be of the same custom font with different size 10.

Is there any way I could try to apply different font sizes only to <small> tag alone? I tried various approaches but I end up applying the style to whole text.

Thanks!!!

First initialize a new mutable attributed string from your html data:

extension NSAttributedString {
    convenience init(data: Data, documentType: DocumentType, encoding: String.Encoding = .utf8) throws {
        try self.init(attributedString: .init(data: data, options: [.documentType: documentType, .characterEncoding: encoding.rawValue], documentAttributes: nil))
    }
}

let html = """
Play million of songs ad-free across all your devices.* Terms and conditions applied.<br><br><small>* Requires a subscription</small>
"""
do {
    let attrStr = try NSMutableAttributedString(data: Data(html.utf8), documentType: .html)

} catch {
    print(error)
}

then enumerate the attributes in your string and check if the font size is small (10) if small set the font to the desired type and its size to 10 otherwise 20:

attrStr.enumerateAttributes(in: .init(location: 0, length: attrStr.length)) { dict, range, stop in
    var attributes = dict
    if let font = attributes[.font] as? UIFont {
        attributes[.font] = UIFont(name: "Helvetica", size: font.pointSize == 10 ? 10 : 20)
        attrStr.setAttributes(attributes, range: range)
        print((attrStr.string as NSString).substring(with: range))
        print("fontName", font.fontName)
        print("pointSize", font.pointSize)
    }
    
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM