1

我有一个如下字符串:

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:@"*"]];

但这只会加粗第二个和第三个星号。我如何让他们都大胆?

4

3 回答 3

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];
于 2014-05-19T21:43:25.063 回答
1

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:@"*"];
}
于 2014-05-19T21:20:30.117 回答
0

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

为此,您可以使用类似这个相关问题中的例程。

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

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

并将其替换为您的代码:

 [mutableAttributedString addAttribute:NSFontAttributeName value:SOMEBOLDFONT range:NSMakeRange(range.location, 1)];
于 2014-05-19T21:17:54.450 回答