4

我有一个应用程序作为普通应用程序运行,但也有一个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. 不幸的是,这根本不起作用是什么我做错了吗?

4

1 回答 1

8

您需要做的是使用User Defaults系统。它使保存和加载首选项变得非常容易。

在按钮的操作中,您将保存其状态:

- (IBAction)toggleStatusItem:(id)sender {

    // Your existing code...

    // A button's state is actually an NSInteger, not a BOOL, but
    // you can save it that way if you prefer
    [[NSUserDefaults standardUserDefaults] setInteger:[sender state]
                                               forKey:@"MyApp_ShouldShowStatusItem"];
}

在您的应用程序委托(或另一个适当的对象) awakeFromNib中,您将从用户默认值中读取该值:

 NSInteger statusItemState = [[NSUserDefaults standardUserDefaults] integerForKey:@"MyApp_ShouldShowStatusItem"];
 [myStatusItemCheckbox setState:statusItemState];

然后确保在必要时致电removeStatusItem

此过程将适用于您可能想要保存的几乎所有首选项。

于 2011-04-22T19:46:25.700 回答