how to enable/disable NSToolbarItem

自古美人都是妖i 提交于 2019-11-30 02:40:41

问题


I have a project that needs to disable/enable some NSToolbarItems depends on different options. I checked and found no parameter for this.

Is there a way to enable/disable a given NSToolbarItem?


回答1:


Implement NSToolbarItemValidation Protocol in your window, view or document controller. The documentation gives the following sample code:

-(BOOL)validateToolbarItem:(NSToolbarItem *)toolbarItem {

    BOOL enable = NO;
    if ([[toolbarItem itemIdentifier] isEqual:SaveDocToolbarItemIdentifier]) {

        // We will return YES (enable the save item)
        // only when the document is dirty and needs saving
        enable = [self isDocumentEdited];

    } else if ([[toolbarItem itemIdentifier] isEqual:NSToolbarPrintItemIdentifier]) {

        // always enable print for this window
        enable = YES;
    }
    return enable;
}

You can also use action or tag to determine what toolbar item is being validated. Items are validated frequently, whenever your app is activated or events are dispatched, so they will always be in a valid state.




回答2:


There is an easier solution :

-(BOOL)validateToolbarItem:(NSToolbarItem *)toolbarItem
{

    return [toolbarItem isEnabled] ;
}

that way you can use [yourToolBarItem setEnabled:YES/NO] ; in your code.




回答3:


an easy way to do this in swift, or you could port this to objective c is to just set actions

This Disables the item

Mytoolbar.action = nil

This reEnables it

Mytoolbar.action = "Name of a function"

In doing this you would want to replace your IBAction with function so

@IBAction func blehbleh(sender: AnyObject){ Stuff }

would be changed to

func blehbleh(){ Stuff }



回答4:


As nsij22 said you need to set action.

In Storyboard just ctrl+drag from toolbar item to your code action.



来源:https://stackoverflow.com/questions/8017822/how-to-enable-disable-nstoolbaritem

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