Auto resize popup button

I have seen many different apps that have popup buttons that auto resize based on the selected item. But I have found it difficult locating any example code to implement this. The closest method I found was sizeToFit(), however this just set the button size to fit the maximum popup menu item (it didn’t auto resize the button based on what was selected).

This was my attempt, which seems to work fine, but if anyone knows of other more efficient methods, please let me know!

I call this method from within my popup menu item action handler.

property myPopUpButton : missing value -- connected in IB to the popup button
property myPopUpMenu : missing value -- connected in IB to the popup's menu

on popUpResize()
		-- Save all menu items
		set menuItems to myPopUpButton's itemArray()
		-- Remove all menu items and replace with the sinlge selected item
		set selectedMenuItem to myPopUpButton's titleOfSelectedItem() as string
		myPopUpMenu's removeAllItems()
		myPopUpMenu's addItemWithTitle_action_keyEquivalent_(selectedMenuItem, "", "")
		-- Resize the popup button to fit the selected item
		myPopUpButton's sizeToFit()
		-- Add all menu items back to the menu
		repeat with menuItem in menuItems
			myPopUpMenu's addItem_(menuItem)
		end repeat
		-- Remove the first item, used to set the button width
		myPopUpMenu's removeItemAtIndex_(0)
		-- Focus the selected menu item
		myPopUpButton's selectItemWithTitle_(selectedMenuItem)
	end popUpResize

Hi brisk,

Does it mean that your popup may expand in size when you open it, if the previous selected item was shorter? Is there any good reason to do so, and are your items so different in size?

I mean, sizeToFit is a deprecated method of NSMenu, or a method of NSMenuView which is used internally.


Hi fiz. What I was really trying to replicate was a borderless popup button, where the arrows beside the title moves so it is always the same distance from the end of the title. This is particularly noticeable if you have a menu item “Small” vs “This is a long title”. If you choose 'Small" the arrow is sitting way off to the right.

However I’ve seen many apple and other apps with bordered popups that change width to fit the title you select, so I thought I’d be able to find some code examples? Thanks.