我对如何在 iOS 项目的文本中使用 SF 符号感到困惑。我有一个 UIButton,它使用
UIImage systemImageNamed:
就可以很好地使用符号。我想在另一个视图中显示有关该按钮的消息和一些文本。我认为我应该能够使用对该符号的 Unicode 引用,但它不呈现。我的理解是这些符号位于私人使用区,但我无法使用像 @"Press the \U0010057C button."
这样的代码来渲染它们
我尝试将 SFSymbolsFallback.ttf 字体文件导入到我的项目中。
我希望看到呈现的符号,但我得到一个?相反。
这对我有用:
let imageAttachment = NSTextAttachment()
imageAttachment.image = UIImage(systemName: "checkmark.circle")
// If you want to enable Color in the SF Symbols.
imageAttachment.image = UIImage(systemName: "checkmark.circle")?.withTintColor(.blue)
let fullString = NSMutableAttributedString(string: "Press the ")
fullString.append(NSAttributedString(attachment: imageAttachment))
fullString.append(NSAttributedString(string: " button"))
label.attributedText = fullString
结果:
我一直在努力解决如何使用 CoreText 渲染 API 使用 SF 符号字形的相同问题。在 MacOS 上,“SF Pro Text”字体中有 7500 多个字形,包括 SF Symbol 字形。在 iOS 上,系统字体只有约 2800 个字形,而且似乎不包括新的 SF Symbol 字形。除了在项目本身中包含字体(我认为这违反了 Apple 的许可),我还没有找到一种方法来使用它们的 Unicode 字符值来呈现这些字形。
在 macOS 13 Ventura 中,您可以简单地将 SF Symbols 应用程序中的符号复制粘贴到 Xcode 中的 NSString 中,效果很好!
我还在 macOS 11 Big Sur 下测试了这个。起初它不起作用,但在我安装 SF Symbols 应用程序后它开始工作了。
所以也许这只有在安装了 SF Symbols 应用程序时才有效?我不确定。
编辑:它似乎与 SF Symbols 应用程序无关,而是与您安装的字体有关。您需要安装某些字体。 SF Pro 之类的,以便 SF 符号在文本中工作。
对于 iOS,此代码段可以为您节省一点时间:
extension NSAttributedString {
static func create(
blocks: [Block],
font: UIFont? = nil,
textColor: UIColor? = nil,
symbolColor: UIColor? = nil
) -> NSAttributedString {
let font = font ?? .preferredFont(forTextStyle: .body)
let textColor = textColor ?? .label
let symbolColor = symbolColor ?? textColor
let attributedBlocks: [NSAttributedString] = blocks.map { block in
switch block {
case .text(let text):
return NSAttributedString(
string: text,
attributes: [
.font: font,
.foregroundColor: textColor
]
)
case .symbol(let imageName):
let attachment = NSTextAttachment()
let imageConfiguration = UIImage.SymbolConfiguration(font: font)
attachment.image = UIImage(
systemName: imageName,
withConfiguration: imageConfiguration
)?.withTintColor(symbolColor)
return NSAttributedString(attachment: attachment)
}
}
let string = NSMutableAttributedString(string: "")
attributedBlocks.forEach {
string.append($0)
}
return string
}
enum Block {
case text(String)
case symbol(String)
}
}
你可能想用 , 或您选择的分隔符。