0

I am trying to add a hyperlink in a string. I have a localized string and I put %@ to format my string. When I add the attributed string into my string, the attributed format gives the raw result which is NSLink = "https://www.example.com". I could not find an attributed string formatter the same as the string formatter. How can I achieve the same behaviour in my case?

Code:

NSMutableAttributedString * str = [[NSMutableAttributedString alloc] initWithString:@"Example"];
[str addAttribute: NSLinkAttributeName value: @"https:/www.example.com" range: NSMakeRange(0, str.length)];
NSMutableAttributedString *originalStr = [[NSMutableAttributedString alloc] initWithString: self.pageDescriptions[3].localized];
pageContentViewController.messageText = [NSString stringWithFormat:self.pageDescriptions[index].localized, str];
Cœur
  • 37,241
  • 25
  • 195
  • 267
jorjj
  • 1,479
  • 4
  • 20
  • 36

2 Answers2

0

stringWithFormat: is only doing substitutions of formatters. So if your formatters are simple enough, like a %@, you can just search for it with rangeOfString: and do the substitution yourself with replaceCharactersInRange:withAttributedString:.

NSMutableAttributedString *strWithLink = [[NSMutableAttributedString alloc] initWithString:@"Example"];
[strWithLink addAttribute:NSLinkAttributeName value:@"https:/www.example.com" range:NSMakeRange(0, strWithLink.length)];

NSMutableAttributedString *strWithFormat = [[NSMutableAttributedString alloc] initWithString:@"hello %@ world"];
[strWithFormat replaceCharactersInRange:[strWithFormat.string rangeOfString:@"%@"] withAttributedString:strWithLink];

The result here in strWithFormat kept the attributes of strWithLink.

Note: this won't work correctly if your format is complex, like with %%@ %@ %%@, because it will replace the first occurrence of %@, while stringWithFormat: would have replaced the middle occurrence.

-1

There isn't one. You create the NSAttributedString by hand, or you create an extension that does what you want if you do this a lot.

gnasher729
  • 51,477
  • 5
  • 75
  • 98