NSMenuItem with attributedTitle containing an NSFont object draws the title with baseline shift

最后都变了- 提交于 2021-01-27 19:31:06

问题


I'm tying to create an NSPopUpButton with the list of fonts available in the system. Seemed pretty obvious task but I've failed. I guess, I'm missing something so obvious that I've completely forgot about it.

The code is pretty straight:

let button = NSPopUpButton()
button.menu = NSMenu()

NSFontManager.shared.availableFonts.forEach { fontNameString in
            let item = NSMenuItem()
            let font = NSFont(name: fontNameString, size: 14)!

            let attrs: [NSAttributedString.Key: Any] = [.font: font]
            item.attributedTitle = NSAttributedString(string: fontNameString, attributes: attrs)

            button.menu?.addItem(item)
}

But that just creates the NSMenu with items having shifted baselines. I've tried to calculate the baseline offset and add it as an attribute but I've failed. Haven't found an algorhythm to satisfy all the font available in the system.

Besides, adding the baseline offset resizes the corresponding NSMenuItem which does not have a fixed size, by the way - the height of an item is different on every font.

To analyse the situation I've added the .backgroundColor attribute and set it to red NSColor. And that brought even more confusing. It appears that some font somehow not drawing in bounds.

How can I center the attributed title vertically? Please, help!

来源:https://stackoverflow.com/questions/65166783/nsmenuitem-with-attributedtitle-containing-an-nsfont-object-draws-the-title-with

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!