[英]How to change a text color for a certain attributed string or make it bold?
Say I have NSString * hello = @"hello world"; 假设我有NSString * hello = @“ hello world”;
Now I want an atributed string where the hell in hello world is bolded. 现在,我需要一个加粗的字符串,在字符串中,hello world中的地狱被加粗。
There is a function on the web that do this: 网路上有个功能可以做到:
- (NSMutableAttributedString*) word:(NSString*)substringToHighlight{
NSMutableAttributedString * mutableAttributedString = [[ NSMutableAttributedString alloc]initWithString:self];
NSUInteger count = 0, length = [mutableAttributedString length];
NSRange range = NSMakeRange(0, length);
count = 0,
length = [mutableAttributedString length];
range = NSMakeRange(0, length);
while(range.location != NSNotFound)
{
range = [[mutableAttributedString string] rangeOfString:substringToHighlight options:0 range:range];
if(range.location != NSNotFound) {
//[mutableAttributedString setTextColor:[UIColor blueColor] range:NSMakeRange(range.location, [word length])];
range = NSMakeRange(range.location + range.length, length - (range.location + range.length));
count++;
}
}
return mutableAttributedString;
}
However, the function doesn't work because mutableAttributedString doestn't support setTextColor 但是,该功能不起作用,因为mutableAttributedString不支持setTextColor
I also tried 我也试过
NSDictionary * dict = @{kCTFontAttributeName:boldFontName};
[mutableAttributedString setAttributes:{kCTFontAttributeName:boldFontName} range:NSMakeRange(range.location, substringToHighlight.length)];
but got a message kCTFontAttributeName is not defined. 但收到一条消息,未定义kCTFontAttributeName。
You can use rangeOfString:options:range: or NSScanner (there are other possibilities like regexps but anyway). 您可以使用rangeOfString:options:range:或NSScanner(还有其他可能,例如regexp,但无论如何)。
Finds and returns the range of the first occurrence of a given string, within the given range of the receiver, subject to given options. 根据给定的选项,在接收器的给定范围内查找并返回给定字符串首次出现的范围。
(NSRange)rangeOfString:(NSString *)aString options:(NSStringCompareOptions)mask range:(NSRange)aRange
This is another solution : 这是另一种解决方案:
Then you need to convert into NSMutableAttributedString
like this way. 然后,您需要像这样将其转换为
NSMutableAttributedString
。
NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:@"hello world"];
NSRange selectedRange = NSMakeRange(0, 4); // 4 characters, starting at index 0
[string beginEditing];
[string addAttribute:NSFontAttributeName
value:[NSFont fontWithName:@"Helvetica-Bold" size:12.0]
range:selectedRange];
[string endEditing];
I think this is the best solution. 我认为这是最好的解决方案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.