0

我有以下代码:

NSMutableAttributedString *attrS = [[NSMutableAttributedString alloc] initWithString:@"• Get Tested Son"];
NSMutableAttributedString *boldS = [[NSMutableAttributedString alloc] initWithString:@"Son"];

[boldS addAttribute:NSFontAttributeName value:SOMEBOLDFONT range:NSMakeRange(0, boldS.length)];

[attrS replaceCharactersInRange:[attrS.string rangeOfString:boldS.string]
           withAttributedString:boldS];

如您所见,我想将这Son部分加粗。如果我执行上述语句,这不起作用,但只有在我这样做时才起作用:

[[attrS mutableCopy] replaceCharactersInRange:[attrS.string rangeOfString:boldS.string]
                         withAttributedString:boldS];

这可能是什么原因?

4

1 回答 1

3

addAttribute无论您是否参加mutableCopy. 你的问题是基于一个错误的假设。因此它没有答案。

运行这个:

NSMutableAttributedString *attrS = [[NSMutableAttributedString alloc] initWithString:@"• Get Tested Son"];
NSMutableAttributedString *boldS = [[NSMutableAttributedString alloc] initWithString:@"Son"];

UIFont *someBoldFont = [UIFont fontWithName:@"Arial" size:23.0f];
[boldS addAttribute:NSFontAttributeName value:someBoldFont range:NSMakeRange(0, boldS.length)];

NSMutableAttributedString *attrSCopy = [attrS mutableCopy];

[attrS replaceCharactersInRange:[attrS.string rangeOfString:boldS.string]
           withAttributedString:boldS];
[attrSCopy replaceCharactersInRange:[attrS.string rangeOfString:boldS.string]
           withAttributedString:boldS];

NSLog(@"%@", [attrS isEqual:attrSCopy] ? @"equal" : @"different");

它将输出equal. 注释掉or replaceCharactersInRange:,它会输出。attrSattrSCopydifferent

于 2014-05-21T21:30:32.393 回答