获取NSlocalized String中参数的索引



这是我的nslocalizedstring:

 "YOUR_INFO" = "%i is the first number,  %i the second and %i the third";

稍后,我正在使用这样的字符串:

 NSString *detailString = [NSString stringWithFormat:NSLocalizedString(@"YOUR_INFO", nil), firstVal, secondVal, thirdVal];

我正在尝试找出变量的索引,以便使用 NSMutableAttributedString以粗体突出显示它们。

我要使用 rangeOfString,但是我意识到如果有两个值相同,可能会有一个问题。有什么方法可以以任何其他智能方式在这些变量的字符串中获得位置?

如果您只想在字符串中向每个数字进行粗体,则可以考虑使用enumerateSubstringsInRange:options:usingBlock:来枚举字符串中的每个单词,并检查它是否为数字(longLongValue)。当您找到数字值时,枚举块为您提供了范围,因此您知道要在属性字符串中修改什么。

使用位置指示符(... %1$i is the first number, %2$i is the second...)。无论如何,您都需要使用本地化的字符串来执行此操作,因为更换的顺序可能会改变。

另一个选项是用一些哨兵模式(例如$>$...$<$)包围待命的值(当然,请确定,即使没有执行任何大胆,请删除哨兵以删除哨兵)。

不错的问题!

我想,不知何故,您将最终编写自己的stringWithFormat版本,换句话说,解析您的本地化字符串。

您可以向后搜索字符串中的所有%i匹配,并应用粗体属性。然后使用replaceCharactersInRange用每个数字的字符串表示手动替换值。根据您的工作方式,向后搜索可能很重要,因为替换字符串会移动下一个值。

  • (void)替换术:( nsrange)arange with string :( nsstring *)累累

新字符继承了第一个替换的属性 来自Arange的角色。arange的长度为0,新的 字符继承Arange之前字符的属性 它具有任何以下字符之后的角色。

尝试以下代码以获取字符串中特定文本/号码的位置。我不知道它对您是否有效..但根据您的要求使用。

    NSString *notiStr;
    int location;
    int length;
    if ([detailString rangeOfString:@"1"].location == NSNotFound)
    {
    }
    else
    {
        location = [notificationString rangeOfString:@"1"].location;
        notiStr = @"1";
        length = 1;
    }
    UIFont *boldFont = [UIFont fontWithName:@"Helvitica-Bold" size:16];
    UIFont *regularFont = [UIFont fontWithName:@"Helvitica-Regular" size:16];
    NSDictionary *attrs = [NSDictionary dictionaryWithObjectsAndKeys:
                                   regularFont, NSFontAttributeName,nil];

    NSDictionary *subAttrs = [NSDictionary dictionaryWithObjectsAndKeys:
                                      boldFont, NSFontAttributeName, nil];
    const NSRange range = NSMakeRange(location,length);
    NSMutableAttributedString *attributedText;
    attributedText = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@",detailedString] attributes:attrs];
    [attributedText setAttributes:subAttrs range:range];

希望它能帮助您..

最新更新