Search code examples
cocoacocoa-touchlocalizationformatnsattributedstring

NSAttributedString from localized string with format specifier


I have a localized string:

"%@ some text" = "%@ some text";

The format specifier %@ may appear in any location in the localized string.

The problem is this string should be an NSAttributedString; the %@ replacement and the rest of the text should have different attributes. How can I solve this issue?


Solution

  • 1) Get your localized template using NSLocalizedString().
    2) Get the text to insert.
    3) Combine the two using -stringWithFormat:.
    4) In the template, find the location of the placeholder using -rangeOfString:
    5) Find the range of the inserted text in the formatted string, using the start position found in the last step, with -rangeOfString:options:range:. (The third argument here is the range within which to search; this avoids finding non-substituted text.)
    6) Create an attributed string from the formatted string, using the range to apply attributes to the inserted text.