0

So I have a formatted String that looks like this:

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

Now, this obviously dosn't work since it returns an NSAttributed String in the middle of a regular String. But how do I make this happen? I need to have the String(format:) to arrange the values in the correct way. But at the same time I need part of the text to be bold.

Joakim Sjöstedt
  • 824
  • 2
  • 9
  • 18

1 Answers1

0

Here is the StringEx library I wrote for this purpose. It allows html tags to be used in the template string, which makes the code more readable:

// 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

You can read more about the library's capabilities from the documentation.

andruvs
  • 79
  • 1
  • 3