macOS 上有很多應用是特別簡單,只在狀態欄上有圖標,點擊之后會彈出一個簡易的 UI,在 UI 上可以進行一系列操作。比如番茄土豆,還有 Alfred 等。
這篇文章主要就是介紹如何創建這些應用。
系統環境 : macOS 10.13 & IDE : Xcode 9.0。
創建好應用之后,需要做一下一些配置:
- 在 info.plist 文件里增加一項設置: Application is agent (UIElement) 為 YES。
- 將 main.storyboard 里面除 Application scene 之外的 scene 全部刪除。
這時候運行工程的話,應該是什么都看不到。
繼續配置,在 AppDelegate.m 里 - (void)applicationDidFinishLaunching:(NSNotification *)aNotification
方法進行寫如下代碼:
statusItem = [[NSStatusBar systemStatusBar] statusItemWithLength:25];
statusItem.image = [NSImage imageNamed:NSImageNameUserGroup];
statusItem.button.target = self;
statusItem.button.action = @selector(hello:);
增加對應方法
- (void)hello:(id)sender {
NSLog(@"hello world");
}
這時候運行工程,狀態欄出現應用圖標:兩個人的 UserGroup 圖片,然后點擊該圖標的時候會輸出"hello world"。
至于怎么點擊應用彈出窗口,也很簡單,具體思路是這樣的: AppDelegate -> WindowController(窗口控制單例) -> Window(.contentView) -> ViewController ->View。
這個命題的關鍵的是設置窗口的位置,為了良好的用戶體驗,窗口應該不會太大導致超出屏幕。
以上。