ios - 循环遍历 NSAttributedString 属性以增加字体大小

标签 ios objective-c 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 有一个新的属性字符串,所有字体都是原始大小的两倍。

关于ios - 循环遍历 NSAttributedString 属性以增加字体大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19386849/

相关文章:

ios - 转换为 NSMutable 属性字符串时 Bad Access 崩溃

objective-c - [__NSCFConstantString pointSize] : unrecognized selector sent to instanc

iOS , WKInterfaceTimer 启动定时器

ios - 在两个压缩音频文件中查找匹配的内容

ios - iOS NSJSONSerialization返回null

objective-c - 如何使用 XCUIElementQuery 测试 UIView 是否存在?

ios - 将日期格式化为固定宽度且不补零

ios - 如何在 iOS 上使用 kCIInputTransformKey

ios - 通过 didSelectRowAtIndexPath 添加 NSManagedObject 到 NSMutableArray

ios - UIImagePickerController 预览大小与实时大小不一样