Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set substrings of NSLocalizedString to be bold

I have a method that sets a NSAttributedString to be bold:

 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 this is how it's called, which works normally:

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

However I am trying to set the text of a substring of an NSLocalizedString to be bold. So I would try it like so:

let formattedString = NSMutableAttributedString()

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

Instead of being "Today starting at 10pm", it gives the following output:

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

Can anyone tell me where I am going wrong or how I can fix this? The reason I have another method is because I have many LocalizedStrings to set bold and thought this might be a simple solution. Open to other ideas/solutions that don't involve lots of repetition/lines of code.

like image 353
coderdojo Avatar asked Jul 27 '16 16:07

coderdojo


1 Answers

I'd just make the outer string html and let AttributedString handle the heavy lifting. This is swift 3, but swift 2.3 should be just as straight-forward. There's also some optional handling to be added, but you get the gist of it.

// 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
)!
like image 109
David Berry Avatar answered Oct 20 '22 00:10

David Berry