【问题标题】:Objective-C: Equivalent to stringWithFormat for NSMutableAttributedStringObjective-C:等效于 NSMutableAttributedString 的 stringWithFormat
【发布时间】:2020-02-06 18:12:17
【问题描述】:

我正在尝试在字符串中添加超链接。我有一个本地化的字符串,我把 %@ 用来格式化我的字符串。当我将属性字符串添加到我的字符串中时,属性格式给出的原始结果是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];

【问题讨论】:

    标签: ios objective-c nsattributedstring nsmutableattributedstring stringwithformat


    【解决方案1】:

    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: 将替换中间出现的位置。

    【讨论】:

      【解决方案2】:

      没有。您可以手动创建 NSAttributedString,或者创建一个扩展来满足您的需求,如果您经常这样做的话。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-07-28
        相关资源
        最近更新 更多