Set NSLocalizedString substrings to be in bold

I have a method that sets NSAttributedString :

 func setBold(text: String) -> NSMutableAttributedString {

    guard let font = UIFont.CustomNormalBoldItalic() else {
        fatalError("font not found")
    }

    let string = NSMutableAttributedString(string:"\(text)", attributes: [NSFontAttributeName : font])

    self.setAttributedString(string)
    return self
}

And here is what it is called, which works fine:

let formattedString = NSMutableAttributedString()
formattedString.setBold("Your text here")

However, I am trying to set the substring text to NSLocalizedString so that it is bold. So I would try like this:

let formattedString = NSMutableAttributedString()

return NSAttributedString(string: String.localizedStringWithFormat(
    NSLocalizedString("message", comment: ""), 
    formattedString.setBold(NSLocalizedString("message.day", comment: "")),
    NSLocalizedString("message.time", comment: "")
))

Instead of " Today, starting at 10 pm", he gives the following result:

Today{
NSFont = "<UICTFont: 0x7fb75d4f1330> font-family: \"CustomText-MediumItalic\"; font-weight: normal; font-style: italic; font-size: 14.00pt";
} starting at 10pm {
}

Can someone tell me where I'm wrong, or how can I fix this? The reason I have another method is because I have many localized strings to set the bold and thought it might be a simple solution. Open to other ideas / solutions that do not contain many repetitions / lines of code.

+4
1

html AttributedString . 3, 2.3 . ​​ , .

// samples so I don't have to put a string resource in my playground, you
// could just as easily pull these from NSLocalizedString
let format = "<b>%1$@</b> starting at <b>%2$@</b>"
let day = "Today"
let time = "10 PM"
let raw = String(format:format, day, time)

let attr = AttributedString(
    html: raw.data(using: .utf8)!, 
    options: [NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType],
    documentAttributes:nil
)!
+1

Source: https://habr.com/ru/post/1649313/


All Articles