[英]How do I bold multiple instances of a character in an NSString?
我有一个类似以下的字符串:
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:@"*"]];
但这只会加粗第二和第三个星号。 如何使它们全部加粗?
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:@"*"];
}
正如其他人提到的那样,您需要遍历字符串以返回多个范围。 这将工作:
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];
每次在字符串中遇到“ *
”字符时,您都需要查找。
为此,您可以使用类似此相关问题中的例程的例程。
您唯一需要从代码中删除此行的内容是:
[mutableAttributedString setTextColor:color range:NSMakeRange(range.location, 1)];
并将其替换为您的代码:
[mutableAttributedString addAttribute:NSFontAttributeName value:SOMEBOLDFONT range:NSMakeRange(range.location, 1)];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.