保存首选项以显示或隐藏NSStatusItem
|
我有一个可以正常运行的应用程序,但也有一个“ 0”。
我想实现在首选项中设置一个复选框的功能,当此复选框打开时,应显示状态项,但是当该复选框关闭时,应删除状态项或使其不可见。
我在这里的论坛中发现有人面临类似问题:如何使用复选框切换菜单栏中的状态项?
但是此解决方案的问题在于它无法按预期工作。因此,我选中了此复选框,并且一切正常,但是当我第二次打开该应用程序时,该应用程序无法识别我在第一次运行时所做的选择。这是因为该复选框未绑定到ѭ1之类的东西,该复选框仅具有
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.
不幸的是,这根本不起作用我在做什么错?
没有找到相关结果
已邀请:
1 个回复
篮肥炼皖
然后在应用程序委托的(或另一个适当的对象)“ 11”中,您将从用户默认值中读取该值:
然后确保在必要时致电
。 此过程几乎适用于您可能要保存的所有首选项。