循环访问NSAttributedString属性以增加字体

我所需要的是循环遍历NSAttributedString所有属性,并增加它们的字体大小。 到目前为止,我已经到了成功循环和操作属性的地步,但是我不能保存回NSAttributedString 。 我注意到的线路不适合我。 如何保存?

 NSAttributedString *attrString = self.richTextEditor.attributedText; [attrString enumerateAttributesInRange: NSMakeRange(0, attrString.string.length) options:NSAttributedStringEnumerationReverse usingBlock: ^(NSDictionary *attributes, NSRange range, BOOL *stop) { NSMutableDictionary *mutableAttributes = [NSMutableDictionary dictionaryWithDictionary:attributes]; UIFont *font = [mutableAttributes objectForKey:NSFontAttributeName]; UIFont *newFont = [UIFont fontWithName:font.fontName size:font.pointSize*2]; [mutableAttributes setObject:newFont forKey:NSFontAttributeName]; //Error: [self.richTextEditor.attributedText setAttributes:mutableAttributes range:range]; //no interfacce for setAttributes:range: }]; 

像这样的东西应该工作:

 NSMutableAttributedString *res = [self.richTextEditor.attributedText mutableCopy]; [res beginEditing]; __block BOOL found = NO; [res enumerateAttribute:NSFontAttributeName inRange:NSMakeRange(0, res.length) options:0 usingBlock:^(id value, NSRange range, BOOL *stop) { if (value) { UIFont *oldFont = (UIFont *)value; UIFont *newFont = [oldFont fontWithSize:oldFont.pointSize * 2]; [res removeAttribute:NSFontAttributeName range:range]; [res addAttribute:NSFontAttributeName value:newFont range:range]; found = YES; } }]; if (!found) { // No font was found - do something else? } [res endEditing]; self.richTextEditor.attributedText = res; 

在这一点上, res有一个新的属性string,所有字体都是原始大小的两倍。

在开始之前,从原始的属性string中创build一个NSMutableAttributedString 。 在循环的每次迭代中,在可变属性string上调用addAttribute:value:range:这将replace该范围中的旧属性)。