1

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?

jscs
  • 63,694
  • 13
  • 151
  • 195
Vyachaslav Gerchicov
  • 2,317
  • 3
  • 23
  • 49

2 Answers2

0

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.

jscs
  • 63,694
  • 13
  • 151
  • 195
  • It won't work if localized template already contains text to insert before step 2. For example: insert "Hello" into "Hello world! %@". My current solution is similar but I create string attributes for "%@" substring and save its range. Then when I insert string - this range changes its length param only. – Vyachaslav Gerchicov Jun 12 '17 at 12:21
  • I'll amend, @VyachaslavGerchicov – jscs Jun 12 '17 at 12:34
-3

You can use NSMutableAttributedString for this case. Here is Apple documentation

 NSString *textToDisplay = [NSString stringWithFormat:@"%@ somet text",localizedString];
 NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:textToDisplay];
       [attrStr addAttribute:NSFontAttributeName
                       value:[UIFont fontWithName:@"Exo2-Regular" size:30]
                       range:NSMakeRange(0, locatilzedString.length)];
       [attrStr addAttribute:NSFontAttributeName
                       value:[UIFont fontWithName:@"Exo2-Bold" size:30]
                       range:NSMakeRange(locatilzedString.length, attrStr.length)];

label.attributedText = attrStr
Clown
  • 163
  • 1
  • 12