我有一个应用程序作为普通应用程序运行,但也有一个NSStausItem
. 我想实现在首选项中设置一个复选框的能力,当这个复选框打开时,状态项应该被显示,但是当复选框关闭时,状态项应该被删除或不可见。
我在这里的论坛中发现有人面临类似问题:如何使用复选框打开和关闭菜单栏中的状态项?
但是我对这个解决方案的问题是它不能按预期工作。所以我勾选了这个复选框,一切正常,但是当我第二次打开应用程序时,应用程序无法识别我在第一次运行时所做的选择。这是因为复选框没有绑定到 aBOOL
或其他东西,复选框只有一个IBAction
,它在运行时删除或添加状态项。
所以我的问题是:如何在首选项中制作一个复选框,让我选择是否显示状态项。
好的,实际上我尝试了以下我从给你链接的帖子中复制了
在 AppDelegate.h 中:
NSStatusItem *item;
NSMenu *menu;
IBOutlet NSButton myStatusItemCheckbox;
然后在 Delegate.m 中:
- (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;
}
- (void)removeStatusItem
{
NSStatusBar *bar = [NSStatusBar systemStatusBar];
[bar removeStatusItem:item];
[item release];
}
- (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];
}
然后在 IBaction 我添加了这个:
[[NSUserDefaults standardUserDefaults] setInteger:[sender state]
forKey:@"MyApp_ShouldShowStatusItem"];
在我的 awakefromnib 中,我添加了这个:`
NSInteger statusItemState = [[NSUserDefaults standardUserDefaults] integerForKey:@"MyApp_ShouldShowStatusItem"];
[myStatusItemCheckbox setState:statusItemState];
然后在界面生成器中,我创建了一个新的复选框,将其与“myStatusItemCheckbox”连接起来,并添加了一个 IBaction,我还单击了绑定检查器并设置了以下绑定到的值:NSUserDefaultController
并且正如ModelKeyPath
我设置的那样:MyApp_ShouldShowStatusItem.
不幸的是,这根本不起作用是什么我做错了吗?