通常のアプリとして実行されるが、もあるアプリケーションがありますNSStausItem
。環境設定でチェックボックスを設定する機能を実装したかったのですが、このチェックボックスをオンにするとステータス項目が表示されますが、チェックボックスをオフにするとステータス項目を削除するか非表示にする必要があります。
ここのフォーラムで同様の問題に直面している人を見つけました。チェックボックスを使用してメニューバーのステータス項目のオンとオフを切り替えるにはどうすればよいですか?
しかし、このソリューションで私が抱えている問題は、期待どおりに機能しないことです。したがって、このチェックボックスをオンにすると、すべて正常に機能しますが、アプリケーションを2回開くと、アプリは最初の実行時に行った選択を認識しません。これは、チェックボックスがaなどにバインドされていないため、チェックボックスには、実行時にステータス項目を削除または追加する、BOOL
のみが含まれているためです。IBAction
だから私の質問は、ステータス項目を表示するかどうかを選択できる設定のチェックボックスを作成するにはどうすればよいですか。
OK、実際に私は次のことを試しました私はあなたにリンクを与えた投稿からコピーしました
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];
NSUserDefaultController
次に、Interface Builderで、「myStatusItemCheckbox」に接続する新しいチェックボックスを作成し、IBactionを追加しました。また、バインディングインスペクターをクリックして、次のバインド先の値を設定しましたModelKeyPath
。MyApp_ShouldShowStatusItem.
残念ながら、これはまったく機能しません。私は間違っていますか?