Pregunta

I need to detect that an NSToolbar has created (or will create) an overflow menu and potentially adjust the window size to make the overflow disappear. But I can't find a simple way to detect that overflow has happened.

¿Fue útil?

Solución

NSToolbar has two methods that can be used to figure this out. -items returns all the current items in the toolbar, including those in the overflow menu. -visibleItems returns only the items that are visible, not including those in the overflow menu. If the arrays returned by these two methods don't match (or just don't contain the same number of items), you know that the toolbar has overflown. Overflow status can change as the window resizes, or when items are added to or removed from the toolbar. So, you can do something like this:

- (void)checkForToolbarOverflow
{
    if ([[self.toolbar items] count] > [[self.toolbar visibleItems] count]) {
        NSLog(@"Overflow!");
    } else {
        NSLog(@"No overflow");
    }
}

- (void)windowDidResize:(NSNotification *)notification
{
    [self checkForToolbarOverflow];
}

- (void)toolbarDidRemoveItem:(NSNotification *)notification
{
    [self checkForToolbarOverflow];
}

- (void)toolbarWillAddItem:(NSNotification *)notification
{
    [self checkForToolbarOverflow];
}

This has one bug, which is that it will incorrectly report no overflow if a new item is added at the end of the toolbar, and that item causes overflow. It turns out that by the time -toolbarWillAddItem: is called, the item-to-be-added is not in the items or visibleItems arrays (as you would expect, since it hasn't been added yet). However, the visibleItems array has been updated to reflect the newly-non-visible items. This works great as long as the new item is not the only non-visible item, since it won't be in the items array either.

My workaround for this isn't ideal, but I haven't come up with something better. It's simply to wait for a short delay after -toolbarWillAddItem returns, giving time for the item to actually be added, then check for overflow again.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top