2

假设我有 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 未定义。

4

1 回答 1

6

You can use rangeOfString:options:range: or NSScanner (there are other possibilities like regexps but anyway).

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 *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.

于 2013-01-30T05:49:58.703 回答