我有一个如下字符串:
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:@"*"]];
但这只是第二和第三个星号的加粗。我怎么把它们全都搞清楚?
答案 0 :(得分: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:@"*"];
}
答案 1 :(得分: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 :(得分:0)
每次在字符串中遇到“*
”字符时都需要找到。
为此,您可以使用found in this related question之类的例程。
您唯一需要从代码中删除此行:
[mutableAttributedString setTextColor:color range:NSMakeRange(range.location, 1)];
并将其替换为您的代码:
[mutableAttributedString addAttribute:NSFontAttributeName value:SOMEBOLDFONT range:NSMakeRange(range.location, 1)];