如何使用复选框打开和关闭菜单栏中的状态项?

Jos*_*hua 0 cocoa objective-c

我已经为菜单栏创建了一个状态项,但我想添加一个复选框,以便能够打开和关闭它.

因此,如果选中该复选框,则会显示状态项,如果未选中该复选框,则不会显示该状态项.

我需要做什么代码?

Ale*_*ski 8

首先在您的控制器类中创建一个实例变量来保存对该项的引用:

NSStatusItem *item;
Run Code Online (Sandbox Code Playgroud)

然后在选中该框时创建一个创建此状态项的方法:

- (BOOL)createStatusItem
{
NSStatusBar *bar = [NSStatusBar systemStatusBar];

//Replace NSVariableStatusItemLength with NSSquareStatusItemLength if you
//want the item to be square
item = [bar statusItemWithLength:NSVariableStatusItemLength];

if(!item)
  return NO;

//As noted in the docs, the item must be retained as the receiver does not 
//retain the item, so otherwise will be deallocated
[item retain];

//Set the properties of the item
[item setTitle:@"MenuItem"];
[item setHighlightMode:YES];

//If you want a menu to be shown when the user clicks on the item
[item setMenu:menu]; //Assuming 'menu' is a pointer to an NSMenu instance

return YES;
}
Run Code Online (Sandbox Code Playgroud)

然后创建一个方法以在取消选中时删除该项:

- (void)removeStatusItem
{
NSStatusBar *bar = [NSStatusBar systemStatusBar];
[bar removeStatusItem:item];
[item release];
}
Run Code Online (Sandbox Code Playgroud)

现在通过创建一个在切换复选框时调用的操作将它们组合在一起:

- (IBAction)toggleStatusItem:(id)sender
{
BOOL checked = [sender state];

if(checked) {
  BOOL createItem = [self createStatusItem];
  if(!createItem) {
    //Throw an error
    [sender setState:NO];
  }
}
else
  [self removeStatusItem];
}
Run Code Online (Sandbox Code Playgroud)

然后在IB中创建复选框并将操作设置为您的toggleStatusItem:方法; 确保未选中该复选框.

编辑(响应错误) 如上所述,您需要NSStatusItem在已放置createStatusItemremoveStatusItem方法的类的接口中声明; 这成为实例变量而不是createStatusItem方法的一个本地变量的原因是无法检索指向已添加到Apple菜单中状态栏的项目的指针,并且为了删除该项目一次如果未选中该复选框,则必须存储指向此项目的指针.这也将解决您的第三个错误.

为了回应您的第二个错误,我只是在演示如果您想在单击时向状态项添加菜单,则必须自己添加代码,检索指向的状态项NSMenu; 我正在展示如何将此菜单项添加到状态栏项,如果您的指针被调用menu,那么我的注释旁边的代码行.