【问题标题】:Generate dynamic text attribute by pattern按模式生成动态文本属性
【发布时间】:2017-11-12 11:21:55
【问题描述】:

我有一个这样的字符串

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

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

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

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

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

提前致谢。

【问题讨论】:

    标签: ios swift uilabel nsattributedstring nsattributedstringkey


    【解决方案1】:

    您可以使用正则表达式的replaceOccurrences来匹配粗体和斜体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)
    }
    

    【讨论】:

    • 感谢您的帮助。它正在工作,但向我显示有关“+ [CATransaction synchronize] 在事务中调用”的警告,您知道它是什么以及如何使其静音
    • @user3783161 我认为这与上面的代码无关。尝试隔离您的问题,如果您发布示例项目,我可以查看它。
    • 感谢帮助我,我找出问题并解决了
    猜你喜欢
    • 2023-03-09
    • 2014-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-26
    • 1970-01-01
    • 2021-02-24
    • 1970-01-01
    相关资源
    最近更新 更多