【问题标题】:How do I use an attributed string inside a formatted string?如何在格式化字符串中使用属性字符串?
【发布时间】:2020-08-26 11:55:30
【问题描述】:

所以我有一个格式化的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)
    }
}

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

【问题讨论】:

标签: ios swift string nsattributedstring


【解决方案1】:

这是我为此目的编写的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 阅读有关该库功能的更多信息。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-30
    • 1970-01-01
    • 2020-04-19
    相关资源
    最近更新 更多