0

這NSMutableAttributedString的addAttribute工作,我有以下代碼:爲什麼只有當我使用mutableCopy

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]; 

什麼可能是其中的原因:如果我做上述表述的,但只有工作,如果我這樣做不行?

+2

它不起作用?你在哪裏調用'addAttribute'? –

+1

我沒有看到你粗體的地方'NSMutableAttributedString':你所做的就是改變同一個字符串的字符串。有沒有'addAttributes'或類似的東西,你忘了在這裏發佈? – Emilie

+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:註釋爲attrSattrSCopy,它將輸出different

相關問題