Search code examples
iosobjective-cswiftmacosnsmenu

Custom NSMenuItem with right-aligned detail text label


What I want to implement

I am looking for a way to display a title label and a detail text label in a NSMenuItem. Preferably it would look something like this: NSMenuItem Example

  1. The Title Label is left aligned with all the other NSMenuItem's titles
  2. The Detail Text Label is right-aligned
  3. The Detail Text Label has a different text color than the title
  4. Selection/Submenus etc. work as expected

What have I tried already

By reading the documentation I found the following possible implementations:

  1. Create a custom NSView and set NSMenuItem.view
  2. Use a default NSMenuItem and use a NSAttributedString

First I tried to use a custom NSView. However I could not get the NSMenuItem to size correctly in order to display all the available text. I guess some autoresizing masks do not work correctly but I am not sure. Also this way I would need to re-implement selection/arrow for the submenu, ...

Then I started to experiment with NSAttributedString. I calculate the title with the most characters and then pad the string with title += string.padding(toLength: maxTitleLength, withPad: " ", startingAt: 0). The NSAttributedString colors the title and the detail label differently. However this does not seem to work since the detail labels are not correctly aligned although the title is padded to the same length. I guess this makes sense since characters have different widths?


TL;DR - Question

So is there any other way to implement the desired design which I did not find? Do you have any advice for me on how to implement this?


Solution

  • I am the creator of the app in the screenshot. These are standard NSMenuItems, not custom views. It is just a NSAttributedString with NSTextTab(type: .rightTabStopType, location: longestTitleWidth) and different text color.