通过NSAttributedString属性循环以增加字体SIze [英] Looping Through NSAttributedString Attributes to Increase Font SIze
本文介绍了通过NSAttributedString属性循环以增加字体SIze的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要的是循环遍历 NSAttributedString
的所有属性并增加它们的字体大小。到目前为止,我已经到了成功循环并操纵属性的地步,但我无法保存回 NSAttributedString
。我评论出的这条线不适合我。如何保存?
All I need is to loop through all attributes of NSAttributedString
and increase their font size. So far I got to the point where I successfully loop through and manipulate attributes but I cannot save back to NSAttributedString
. The line I commented out is not working for me. How to save back?
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
有一个新的归因字符串,所有字体都是原始大小的两倍。
At this point res
has a new attributed string with all fonts being twice their original size.
这篇关于通过NSAttributedString属性循环以增加字体SIze的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文