我有以下代码:
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];
可能是什么原因?
答案 0 :(得分: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
。为replaceCharactersInRange:
或attrS
注释掉attrSCopy
,然后输出different
。