How do you toggle the status item in the menubar on and off using a checkbox?

后端 未结 2 1185
隐瞒了意图╮
隐瞒了意图╮ 2021-01-07 15:23

I have already created a status item for the menu bar but I would like to add a checkbox to make it able to be toggled on and off.

So when the check box is checked t

2条回答
  •  隐瞒了意图╮
    2021-01-07 15:51

    First in your controller class create an instance variable to hold the reference to this item:

    NSStatusItem *item;
    

    Then create a method to create this status item, when the box is checked:

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

    Then create a method to remove the item when it is unchecked:

    - (void)removeStatusItem
    {
    NSStatusBar *bar = [NSStatusBar systemStatusBar];
    [bar removeStatusItem:item];
    [item release];
    }
    

    Now tie it all together by creating an action that is called when the checkbox is toggled:

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

    Then create the checkbox in IB and set the action to your toggleStatusItem: method; make sure that the checkbox is left unchecked.

    Edit (In response to errors) As stated above, you need to declare the NSStatusItem in the interface of the class that you have placed the createStatusItem and removeStatusItem methods; the reason that this becomes an instance variable rather than one local to the createStatusItem method is that there is no way to retrieve a pointer to an item that has already been added to the status bar in the Apple menu, and in order to remove the item once the checkbox is unchecked, you must store a pointer to this item. This will also solve your third error.

    In response to your second error, I was merely demonstrating that if you want to add a menu to your status item when it is clicked, you must add the code for that yourself, retrieving a pointer to an NSMenu; I was showing how you could then add this menu item to the status bar item, if your pointer was called menu, hence my comment next to the line of code.

提交回复
热议问题