2011-11-05 30 views
9

我有一個項目,需要禁用/啓用一些NSToolbarItems取決於不同的選項。我查了一下,發現沒有參數。如何啓用/禁用NSToolbarItem

有沒有辦法啓用/禁用NSToolbarItem?

回答

9

在窗口,視圖或文檔控制器中實現NSToolbarItemValidation協議。該文檔提供了下面的示例代碼:

-(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; 
} 

您還可以使用actiontag以確定正在驗證什麼工具欄項目。每當您的應用程序被激活或事件分派時,項目都會經常驗證,因此它們將始終處於有效狀態。

7

有一個更簡單的解決方案:

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

    return [toolbarItem isEnabled] ; 
} 

這樣你可以使用[yourToolBarItem的setEnabled:YES/NO]。在你的代碼中。

+1

絕妙的主意! –

+1

乾淨漂亮,在面料類 –

2

一種簡單的方式迅速做到這一點,或者你可以口這客觀C對於剛剛成立的行動

這將禁用項目

Mytoolbar.action = nil 

這將重新啓用它

Mytoolbar.action = "Name of a function" 

在這樣做,你會想用功能替換你的IBAction所以

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

正如nsij22說你需要設置的行動將改爲

func blehbleh(){ Stuff } 
0

在故事板中按住ctrl +從工具欄項拖動到代碼動作。