【问题标题】:How do I bold multiple instances of a character in an NSString?如何在 NSString 中加粗一个字符的多个实例?
【发布时间】:2014-05-19 21:02:52
【问题描述】:

我有如下字符串:

NSString *a = @"* This is a text String \n * Followed by another text String \n * Followed by a third"

我需要将它打印为三行。现在,我希望将其中的 Asterix 点加粗。所以我尝试了:

NSMutableAttributedString *att = [[NSMutableAttributedString alloc] initWithString:a];
[att addAddtribute:NSFontAttributeName value:SOMEBOLDFONT range:[a rangeOfString:@"*"]];

但这只会加粗第二个和第三个星号。如何让它们全部加粗?

【问题讨论】:

  • 字符串中似乎只有两个星号,错字?
  • 该代码无法编译。我真的建议您发布您所询问的实际代码。

标签: ios objective-c nsstring nsmutableattributedstring bulletedlist


【解决方案1】:

正如其他人所提到的,您需要遍历字符串以返回多个范围。 这会起作用:

NSString *a = @"* This is a text String \n* Followed by another text String \n* Followed by a third";
NSMutableAttributedString *att = [[NSMutableAttributedString alloc] initWithString:a];
NSRange foundRange = [a rangeOfString:@"*"];

while (foundRange.location != NSNotFound)
{
    [att addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:20.0f] range:foundRange];

    NSRange rangeToSearch;
    rangeToSearch.location = foundRange.location + foundRange.length;
    rangeToSearch.length = a.length - rangeToSearch.location;
    foundRange = [a rangeOfString:@"*" options:0 range:rangeToSearch];
}

[[self textView] setAttributedText:att];

【讨论】:

  • 最后还是这样做了。谢谢!
【解决方案2】:

rangeOfString 只返回一个范围而不是所有范围。循环并设置所有范围

NSRange range = [event1 rangeOfString:@"*"];

while (range.length > 0)
{
    [att addAddtribute:NSFontAttributeName value:SOMEBOLDFONT range:[a rangeOfString:@"*"]];
     //check for the presence of * in the rest of the string
    range = [[event1 substringFromIndex:(range.location + range.length)] rangeOfString:@"*"];
}

【讨论】:

  • 谢谢。这也是一个非常简洁的答案。
【解决方案3】:

每次在字符串中遇到“*”字符时都需要查找。

为此,您可以使用像found in this related question 这样的例程。

您唯一需要从代码中删除这一行:

[mutableAttributedString setTextColor:color range:NSMakeRange(range.location, 1)];

并将其替换为您的代码:

 [mutableAttributedString addAttribute:NSFontAttributeName value:SOMEBOLDFONT range:NSMakeRange(range.location, 1)];

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-20
    • 2022-11-02
    • 2013-09-22
    • 1970-01-01
    • 1970-01-01
    • 2012-01-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多