How can I change the height of an NSMenuItem? When I change the font of a menu, an NSMenuItem automatically resizes to just fit the title, leaving no space above or below the title. It looks very cramped.

Looks like this:

enter image description here

Want it to look like this:

enter image description here

I've tried a million tweaks related to the attributed title of the menu items, but to no avail. I also don't want to use the view property of the menu items because I want to keep the highlight. Any other ideas?

Edit: This is what I'd like (more or less), but based on NSMenu, not redoing it from the ground up.

enter image description here

有帮助吗?

解决方案

You can set an empty 1-pixel wide image with the desired height:

NSImage *image=[[NSImage alloc]initWithSize:NSMakeSize(1,30)];

[menuItem setImage:image];

Obviously you end up with titles that are offset 1 pixel to the right, though that may be acceptable if uniformly applied.

其他提示

// you want height 100    
[menuItem setView:[[NSView alloc] initWithFrame:NSMakeRect(0, 0, 0, 100)]];

An option is to use NSAttributedString as following:

let font = NSFont.systemFont(ofSize: NSFont.systemFontSize)
let fontLineHeight = (font.ascender + abs(font.descender))
let lineHeight: CGFloat = fontLineHeight * 1.4
let style = NSMutableParagraphStyle()
style.minimumLineHeight = lineHeight
style.maximumLineHeight = lineHeight
let baselineOffset = (lineHeight - fontLineHeight) / 2
let item = NSMenuItem()
item.attributedTitle = NSAttributedString(string: title,
                                          attributes: [
                                            .paragraphStyle: style,
                                            .baselineOffset: baselineOffset
                                          ])

If you are looking for a re-implementation of NSMenu based upon NSWindow rather than the Carbon side of things check out JGMenuWindow:

https://github.com/SquaredTiki/JGMenuWindow

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top