Are there approaches to using attribute strings in conjunction with localization?

Suppose there is this line in English and its requirement to highlight in bold or color, etc. for a specific part of a line of text:

"word1 word2 WORD3 word4"

This can be done by setting the attribute for the appropriate range.

The range can be hard-coded (13.5), but then, of course, it will not be localizable.

Thus, a range can be dynamically determined, knowing that its third word, which should be in bold, is applied to it.

But this is also not localized. Suppose that if this sentence is translated into N, it contains only 2 words or contains 5 words in M?

So my question is, how can you use attribute strings in combination with localization without a lot of hard coding?

+6
source share
3 answers

You can use some notation to indicate which words should be shown in bold and then have a transformer that will display ranges in bold and add the appropriate attributes.

word β€’wordβ€’ word word

ΧžΧ™ΧœΧ” ΧžΧ™ΧœΧ” β€’ΧžΧ™ΧœΧ”β€’ ΧžΧ™ΧœΧ” ΧžΧ™ΧœΧ”

In these two sentences, I use the symbol β€’ to indicate that the word between them should be bold. Then I can use rangeOfString:options:range: to iterate and search all the ranges in bold, and insert the attribute accordingly.

+3
source

The approach I take with my last project is to use HTML in the Localizable.strings file, and then use something like this to create an 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 it all up in #define LocalizedHTMLForKey(key) , so I hope I haven't added any typos to this answer, making it legible ...)

+8
source

Answering a Bens question, I created an extension to help me do this in Swift.

 extension NSAttributedString { convenience init?(withLocalizedHTMLString: String) { guard let stringData = withLocalizedHTMLString.data(using: String.Encoding.utf8) else { return nil } let options: [String : Any] = [ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType as AnyObject, NSCharacterEncodingDocumentAttribute: String.Encoding.utf8.rawValue ] try? self.init(data: stringData, options: options, documentAttributes: nil) } } 

Use this initializer with your HTML tag string, for example. "By signing up, you agree to our <u><b>Terms & Privacy Policy</b></u>"; and he must do all the work for you!

+2
source

All Articles