[英]How do I bold multiple instances of a character in an NSString?
I have a string like the following : 我有一个类似以下的字符串:
NSString *a = @"* This is a text String \n * Followed by another text String \n * Followed by a third"
I need to print it as three lines. 我需要将其打印为三行。 Now, I wanted the Asterix points in it to be bolded.
现在,我希望其中的Asterix点加粗。 So I tried :
所以我尝试了:
NSMutableAttributedString *att = [[NSMutableAttributedString alloc] initWithString:a];
[att addAddtribute:NSFontAttributeName value:SOMEBOLDFONT range:[a rangeOfString:@"*"]];
But this only bolds the second and third asterix. 但这只会加粗第二和第三个星号。 How do I get them all bold?
如何使它们全部加粗?
rangeOfString Returns only one range not all the range. rangeOfString仅返回一个范围,而不是所有范围。 Loop and set all the ranges
循环并设置所有范围
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:@"*"];
}
As others have mentioned, you need to loop through the string to return multiple ranges. 正如其他人提到的那样,您需要遍历字符串以返回多个范围。 This would work:
这将工作:
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];
You need to find each time the " *
" character is encountered in your string. 每次在字符串中遇到“
*
”字符时,您都需要查找。
And to do that, you can use a routine like the one found in this related question . 为此,您可以使用类似此相关问题中的例程的例程。
The only thing you'd need to remove this line from the code: 您唯一需要从代码中删除此行的内容是:
[mutableAttributedString setTextColor:color range:NSMakeRange(range.location, 1)];
and replace it with your code: 并将其替换为您的代码:
[mutableAttributedString addAttribute:NSFontAttributeName value:SOMEBOLDFONT range:NSMakeRange(range.location, 1)];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.