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

标签 ios ios7 attributes nsattributedstring uifont

我有一个现有的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/

相关文章:

ios - 我可以在我的 iPhone 上安装由 release(appstore) 配置文件签名的 ipa

ios - xcode-线程 1 : EXC_BAD_ACCESS

ios - 缺少必需的图标文件。该 bundle 不包含 iPhone/iPod Touch 的应用程序图标,正好是 '120x120' 像素

javascript - 测试一下具有 json 值的图像是否损坏/或不存在并替换为 "no-photo"图像?

c# - 创建挂接到属性的 getter 和 setter 的 C# 属性

jQuery 1.4.1 和 Firefox 16.0.1 奇怪的属性问题

iOS - 绘制数千个符号的最佳方式

ios - 无法验证包,未使用苹果提交证书签名

ipad - iOS 7's drawViewHierarchyInRect doesn' t 工作?

iOS 7 + iPad : UISearchBar causes navigation bar content to be mixed with status bar