Objective-C:相当于 NSMutableAttributedString 的 stringWithFormat



我正在尝试在字符串中添加超链接。我有一个本地化的字符串,我输入 %@ 来格式化我的字符串。当我将属性字符串添加到我的字符串中时,属性格式给出了NSLink = "https://www.example.com"的原始结果。我找不到与字符串格式化程序相同的属性字符串格式化程序。在我的案例中,我怎样才能实现相同的行为?

法典:

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];

stringWithFormat:只是对格式化程序进行替换。因此,如果您的格式化程序足够简单,例如%@,您可以使用rangeOfString:搜索它并自己用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];

strWithFormat这里的结果保留了strWithLink的属性。

注意:如果您的格式很复杂,例如%%@ %@ %%@,这将无法正常工作,因为它将替换%@的第一次出现,而stringWithFormat:将替换中间出现的。

没有。您可以手动创建 NSAttributedString,或者如果您经常这样做,则可以创建一个执行所需操作的扩展。

相关内容

  • 没有找到相关文章

最新更新