首页 > 解决方案 > CTFontGetGlyphsForCharacters 传递表情符号时返回 false

问题描述

在符合NSLayoutManagerDelegate我的类中实现此方法:

func layoutManager(_ layoutManager: NSLayoutManager,
                       shouldGenerateGlyphs glyphs: UnsafePointer<CGGlyph>,
                       properties props: UnsafePointer<NSLayoutManager.GlyphProperty>,
                       characterIndexes charIndexes: UnsafePointer<Int>,
                       font aFont: UIFont,
                       forGlyphRange glyphRange: NSRange) -> Int {

        // First, make sure we'll be able to access the NSTextStorage.
        guard let textStorage = layoutManager.textStorage
        else { return 0 }

        // Get the first and last characters indexes for this glyph range,
        // and from that create the characters indexes range.
        let firstCharIndex = charIndexes[0]
        let lastCharIndex = charIndexes[glyphRange.length - 1]
        let charactersRange = NSRange(location: firstCharIndex, length: lastCharIndex - firstCharIndex + 1)
        
        var bulletPointRanges = [NSRange]()
        var hiddenRanges = [NSRange]()
        let finalGlyphs = UnsafeMutablePointer<CGGlyph>(mutating: glyphs)
        
        // Generate the Middle Dot glyph using aFont.
        
        let middleDot: [UniChar] = [0x00B7] // Middle Dot: U+0x00B7
        var myGlyphs: [CGGlyph] = [0]
        
        // Get glyphs for `middleDot` character
        guard CTFontGetGlyphsForCharacters(aFont, middleDot, &myGlyphs, middleDot.count) == true
        else { fatalError("Failed to get the glyphs for characters \(middleDot).") }
}

问题是CTFontGetGlyphsForCharacters当我在文本视图中输入表情符号时返回 false。我认为这可能与 UTF-8 与 UTF-16 有关,但我在这里有点超出我的深度。一点帮助?

标签: swiftunicodeutf-8textviewtextkit

解决方案


您使用的字体没有该特定字符的字形。

当您尝试查看的特定字体没有字形但另一种字体可能时,系统会维护一个“字体后备”列表。

后备列表由 CTFontCopyDefaultCascadeListForLanguages 给出,但由于您正处于被要求提供特定字体的字形的位置,因此后备生成似乎应该在链中更高的位置处理。

您可能应该返回 0 以指示布局管理器应该使用它的默认行为。


推荐阅读