Vad*_*Vad 30 objective-c nsattributedstring ios
我只需循环遍历所有属性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:
}];
Run Code Online (Sandbox Code Playgroud)
rma*_*ddy 55
这样的事情应该有效:
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;
Run Code Online (Sandbox Code Playgroud)
此时res有一个新的属性字符串,所有字体都是原始大小的两倍.
NSMutableAttributedString在开始之前从原始属性字符串创建一个.在循环的每次迭代中,调用addAttribute:value:range:可变属性字符串(这将替换该范围中的旧属性).