gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 16:37:08 25 4
gpt4 key购买 nike

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

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

我看到了一些 different but related threads,建议枚举字符串中的每个属性范围,更改字体,然后重新应用适用的格式属性。这似乎很费力,而且当存在多个属性(即粗体,斜体和下划线)时,我不确定如何应用它。

感谢您的任何建议。

最佳答案

我有完全相同的问题,枚举效果很好。这里的“范围”是您要处理的范围,“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()

关于ios - 保留格式属性时NSAttributedString字体更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27204960/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com