按模式生成动态文本属性

时间:2017-11-12 11:21:56

标签: ios swift uilabel nsattributedstring nsattributedstringkey

我有一个像这样的字符串

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

& &标记内的所有内容都将为斜体,% %内部标记将变为粗体样式,并将此数据设置为UILabel。最终输出将是:

  

这是我的苹果,我昨天买了

已编辑:我使用%(.*?)%作为正则表达式模式来提取子字符串

有什么方法可以解决这个问题吗?请帮忙

提前致谢。

1 个答案:

答案 0 :(得分:1)

你可以使用regex的replacementOccurrences来匹配粗体和斜体html标签,然后使用NSAttributedString将你的html字符串转换为属性字符串。

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)

将您的html转换为属性字符串

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)
}