如何在格式化字符串中使用属性字符串?

问题描述

所以我有一个格式如下的String

let myString = String(format: "%@ %@ \n\n","App Version:".makeBold(),AppSettings.appVersion)

//Extension looks like this
extension String {
    func makeBold() -> NSAttributedString {
        let attribute: [NSAttributedString.Key: Any] = [
            .font: UIFont.OpenSansstyle.bold
        ]
        
        return NSAttributedString(string: self,attributes: attribute)
    }
}

现在,这显然不起作用,因为它在常规NSAttributed String中间返回了String。但是我如何做到这一点呢?我需要使用String(format:)以正确的方式排列值。但同时,我需要部分文字加粗。

解决方法

这是我为此目的编写的 StringEx 库。它允许在模板字符串中使用 html 标签,这使得代码更具可读性:

// Suppose you have a pattern like this
let pattern = "<label /> <value />\n\n"

// Create StringEx instance
let ex = pattern.ex

// Insert values and style
ex[.tag("label")]
    .insert("App Version:")
    .style(.font(.boldSystemFont(ofSize: 16)))

ex[.tag("value")].insert(AppSettings.appVersion)

// Then you can get the result string or NSAttributedString
let string = ex.string
let attributedString = ex.attributedString

myLabel.attributedText = attributedString

您可以从 documentation 中阅读有关该库功能的更多信息。