保留格式属性时NSAttributedString字体更改

时间:2021-09-23 02:12:39

I have an existing NSAttributedString that may include user edited attributes (i.e. Bold, Italic, Underline). I need to be able to change the base font from say Georgia to Helvetica, while maintaining the format attributes. Setting the font like so, overrides all format attributes (i.e. Georgia-Bold):

我有一个现有的NSAttributedString,可能包括用户编辑的属性(即粗体,斜体,下划线)。我需要能够将基本字体从Georgia更改为Helvetica,同时保持格式属性。像这样设置字体,覆盖所有格式属性(即Georgia-Bold):

NSDictionary *fontFaceStyle = [[NSDictionary alloc] init];
fontFaceStyle = @{NSFontAttributeName:[UIFont fontWithName:@"Helvetica" size:12.0]};
[combinedAttributedTextString setAttributes:fontFaceStyle range:NSMakeRange(0, combinedAttributedTextString.length)];

I have seen some different but related threads that suggest enumerating over each attribute span in the string, make font change, then reapply the applicable format attributes. This seems pretty intensive, and I'm not sure how you'd apply it when multiple attributes could be present (i.e. Bold AND Italic AND Underline).

我已经看到一些不同但相关的线程建议枚举字符串中的每个属性跨度,进行字体更改,然后重新应用适用的格式属性。这似乎非常密集,我不确定当多个属性存在时你是如何应用它的(即粗体和斜体和下划线)。

Thanks for any suggestions.

谢谢你的任何建议。

1 个解决方案

#1


0  

I had the exact same issue, and enumerating works well. Here "range" is the range you want to work on, and "newFamily" is a font-family. I am using textStorage, which I assume is doing useful cleanup for these types of edits when wrapping with calls to beginEditing() / endEditing().

我有完全相同的问题,枚举效果很好。这里“range”是你想要处理的范围,“newFamily”是一个字体系列。我正在使用textStorage,我假设在使用beginEditing()/ endEditing()调用包装时对这些类型的编辑进行了有用的清理。

textStorage.beginEditing()
textStorage.enumerateAttributes(in: range, options: [], using: { attr, attrRange, _ in
    if let font = attr[NSFontAttributeName] as? NSFont {
        let newFont = NSFontManager.shared().convert(font, toFamily: newFamily)
        storage.addAttribute(NSFontAttributeName, value: newFont, range: attrRange)
    }
})
textStorage.endEditing()

#1


0  

I had the exact same issue, and enumerating works well. Here "range" is the range you want to work on, and "newFamily" is a font-family. I am using textStorage, which I assume is doing useful cleanup for these types of edits when wrapping with calls to beginEditing() / endEditing().

我有完全相同的问题,枚举效果很好。这里“range”是你想要处理的范围,“newFamily”是一个字体系列。我正在使用textStorage,我假设在使用beginEditing()/ endEditing()调用包装时对这些类型的编辑进行了有用的清理。

textStorage.beginEditing()
textStorage.enumerateAttributes(in: range, options: [], using: { attr, attrRange, _ in
    if let font = attr[NSFontAttributeName] as? NSFont {
        let newFont = NSFontManager.shared().convert(font, toFamily: newFamily)
        storage.addAttribute(NSFontAttributeName, value: newFont, range: attrRange)
    }
})
textStorage.endEditing()