use*_*951 2 objective-c xcode4.5
说我有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;
}
Run Code Online (Sandbox Code Playgroud)
但是,该函数不起作用,因为mutableAttributedString不支持setTextColor
我也试过了
NSDictionary * dict = @{kCTFontAttributeName:boldFontName};
[mutableAttributedString setAttributes:{kCTFontAttributeName:boldFontName} range:NSMakeRange(range.location, substringToHighlight.length)];
Run Code Online (Sandbox Code Playgroud)
但得到了一条消息kCTFontAttributeName未定义.
您可以使用rangeOfString:options:range:或NSScanner(还有其他可能性,如regexps但无论如何).
根据给定的选项,在给定的接收器范围内查找并返回给定字符串第一次出现的范围.
(NSRange)rangeOfString:(NSString *)aString options:(NSStringCompareOptions)mask range:(NSRange)aRange这是另一种解决方案:
然后你需要转换成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];
Run Code Online (Sandbox Code Playgroud)
我认为这是最好的解决方案.
| 归档时间: |
|
| 查看次数: |
8072 次 |
| 最近记录: |