Are there approaches for using attributed strings in combination with localization?
The approach I'm taking with my latest project is to use HTML in the Localizable.strings
file, and then use something like this to generate the NSAttributedString
:
NSString *htmlString = NSLocalizedString(key, comment);
[[NSAttributedString alloc] initWithData:
[htmlString dataUsingEncoding:NSUTF8StringEncoding]
options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
NSCharacterEncodingDocumentAttribute: @(NSUTF8StringEncoding)}
documentAttributes:nil
error:nil]]
(As a personal preference, I wrap this all up into a #define LocalizedHTMLForKey(key)
, so hopefully I've not added any typos into this answer by making it legible…)
You could use some notation to signify which words should be bolded, and then have a transformer that would find ranges to bold and add appropriate attributes.
word •word• word word
מילה מילה •מילה• מילה מילה
In these two sentences, I use the character •
to signify that the word in between should be bold. I can then use rangeOfString:options:range:
to iterate and find all ranges to bold and insert an attribute accordingly.
Harry's answer for Swift 4
extension NSAttributedString {
convenience init?(withLocalizedHTMLString: String) {
guard let stringData = withLocalizedHTMLString.data(using: String.Encoding.utf8) else {
return nil
}
let options: [NSAttributedString.DocumentReadingOptionKey: Any] = [
NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html as Any,
NSAttributedString.DocumentReadingOptionKey.characterEncoding: String.Encoding.utf8.rawValue
]
try? self.init(data: stringData, options: options, documentAttributes: nil)
}
}