[英]Save preference to show or hide NSStatusItem
我有一個應用程序,它作為一個普通的應用程序運行,但也有一個NSStausItem
。 我希望實現在偏好設置中設置復選框的功能,當此復選框打開時,應顯示狀態項,但是當復選框關閉時,狀態項應被刪除或不可見。
我在論壇中發現有人遇到類似問題: 如何使用復選框打開和關閉菜單欄中的狀態項?
但是我對這個解決方案的問題是它沒有按預期工作。 所以我做了這個復選框,一切正常,但是當我第二次打開應用程序時,應用程序無法識別我在第一次運行時所做的選擇。 這是因為復選框沒有綁定到BOOL
或其他東西,復選框只有一個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.
不幸的是,這根本不起作用我做錯了什么?
您需要做的是使用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"];
}
並且在您的app delegate(或其他適當的對象) awakeFromNib
,您將從用戶默認值中讀取該值:
NSInteger statusItemState = [[NSUserDefaults standardUserDefaults] integerForKey:@"MyApp_ShouldShowStatusItem"];
[myStatusItemCheckbox setState:statusItemState];
然后確保在必要時調用removeStatusItem
。
此過程幾乎適用於您可能要保存的任何首選項。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.