假设我有 NSString * hello = @"hello world";
现在我想要一个属性字符串,其中 hello world 中的地狱用粗体显示。
网上有一个功能可以做到这一点:
- (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;
}
但是,该函数不起作用,因为 mutableAttributedString 不支持 setTextColor
我也试过
NSDictionary * dict = @{kCTFontAttributeName:boldFontName};
[mutableAttributedString setAttributes:{kCTFontAttributeName:boldFontName} range:NSMakeRange(range.location, substringToHighlight.length)];
但收到消息 kCTFontAttributeName 未定义。