Search code examples
iosswiftuilabelnsattributedstringnsattributedstringkey

Generate dynamic text attribute by pattern


I have a string like this

var str = "This is &my& apple, I bought it %yesterday%"

Everything inside & & mark will be italics, inside % % mark will turn into bold style and set this data to a UILabel. The final output will be:

This is my apple, I bought it yesterday

Edited: I am using %(.*?)% as a regex pattern to extract the substring

Is there any way to solve this issue? Please help

Thanks in advance.


Solution

  • You can use replacingOccurrences of regex to put the matches between bold and italic html tags and then use NSAttributedString to convert your html string to attributed string.

    let str = "This is &my& apple, I bought it %yesterday%"
    
    let html = str
        .replacingOccurrences(of: "(&.*?&)", with: "<b>"+"$1"+"</b>", options: .regularExpression)
        .replacingOccurrences(of: "&(.*?)&", with: "$1", options: .regularExpression)
        .replacingOccurrences(of: "(%.*?%)", with: "<i>"+"$1"+"</i>", options: .regularExpression)
        .replacingOccurrences(of: "%(.*?)%", with: "$1", options: .regularExpression)
    

    Converting your html to attributed string

    let label = UILabel(frame: CGRect(origin: .zero, size: CGSize(width: 300, height: 50)))
    label.font = UIFont.systemFont(ofSize: 14)
    do {
        label.attributedText = try NSAttributedString(data: Data(html.utf8), options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding: String.Encoding.utf8.rawValue], documentAttributes: nil)
    } catch {
        print("error:", error)
    }